Original Address: https: //www.cnblogs.com/web-record/p/10131782.html
JS acquired DOM element method (8 types)
- Acquiring the ID (the getElementById)
- By name attribute (the getElementsByName)
- By tag name (getElementsByTagName)
- By class name (getElementsByClassName)
- Obtaining an element (querySelector) by the selector
- Obtaining a set of elements (querySelectorAll) by the selector
- Methods (document.documentElement) acquisition of html
- document.documentElement is designed to obtain this label html
- Methods (document.body) get body of
- document.body body is designed to obtain this label.
1. ID acquisition (the getElementById)
document.getElementById('id')
- Context must be a document.
- Must pass parameters, parameter of type string, it is to obtain an element of id.
- To get a return value only element not found return null.
2. name attribute (the getElementsByName)
document.getElementsByName('name')
- Context must be a document. content
- Must pass parameters, parameter is to obtain the element name attribute.
- The return value is an array of class, did not find returns an empty array.
3. by tag name (getElementsByTagName)
var obj = document.getElementsByTagName('div');
for(let i = 0; i<obj.length; i++){
obj[i].onclick = function(e){ console.log(i) } }
- Context can be a document, it can also be an element, pay attention to this element must be present.
- Parameter is to obtain the tag name attribute of the element, not case-sensitive.
- The return value is an array type, returns an empty array not found
4. The class name (getElementsByClassName
var obj1 = document.getElementsByClassName('animated')
// console.log
0:div.app.animated
1:div#login.login.animated.rubberBand 2:div#reg.reg.animated.shake 3:div#kefu.kefu.animated.swing 4:div#LoginState.state.animated.bounce 5:div.loginState.animated 6:div.regState.animated 7:div.pop.animated
- Context may be document, it may be an element.
- Parameter is the class name of the element.
- The return value is an array of class, did not find returns an empty array.
5. Get element by a selector (querySelector)
document.querySelector('.animated')
- Context may be document, it may be an element.
- Parameter is selected, such as: "div .className".
- The return value only get to the first element.
6. Obtain a set of elements (querySelectorAll) by the selector
document.querySelector('.animated')
- Context may be document, it may be an element.
- Parameter is selected, such as: "div .className".
- The return value is an array type.