1. Get Elements
The getElementById () method is used to obtain the element id. If the element id does not exist, null is returned.
Make sure that the name of the form element is not the same as the id of other elements. ie browsers under IE8 can use this method to obtain the element through the name attribute of the element.
The following surface element is used as an example.
<Div id = "myDiv"> here is the div content whose id is "myDiv" </div>
Var document. getElementById ("myDiv"); // "myDiv" case sensitive, get reference to the <div> element
The getElementsByTagName () method obtains an element through the element's tag name. It accepts a parameter, that is, the tag name of the element to be obtained, and returns a NodeList containing 0 or more.
1 var images = document. getElementsByTagName ("img"); // obtain all elements on the page
2
3 alert (images. length); // number of images
4 alert (images [0]. src); // src of the first image Element
5 alert (images. item (0). src); // same as above
The getElementsByName () method obtains an element through the name attribute of the element. It accepts a parameter that is used to obtain the name attribute of the element. It is often used to obtain the single-choice button.
1 <ul>
2 <li> <input type = "radio" name = "color" value = "red" id = "colorRed"> <label for = "colorRed"> </label> </li>
3 <li> <input type = "radio" name = "color" value = "green" id = "colorGreen"> <label for = "colorGreen"> </label> </li>
4 <li> <input type = "radio" name = "color" value = "blue" id = "colorBlue"> <label for = "colorBlue"> </label> </li>
5 </ul>
Var radios = document. getElementsByName ("color"); // obtain all radio buttons for name = "color"
2. Obtain element subnodes or element subnodes and their child nodes
1 <ul id = "myList">
2 <li> Project 1 </li>
3 <li> Project 2 </li>
4 <li> Project 3 </li>
5 </ul>
IE believes that the <ul> element has three subnodes, which are three elements respectively. other browsers will think that there are seven subnodes, including three elements and four text nodes, if <ul> is in a row:
<Ul id = "myList"> <li> Project 1 </li> <li> Project 2 </li> <li> Project 3 </li> </ul>
Any browser considers three subnodes
Obtain the child nodes of an element:
1 var ul = document. getElementById ("myList ");
2 for (var I = 0, len = ul. childNodes. length; I <len; I ++ ){
3 if (ul. childNodes. length [I]. nodeType = 1) {// nodeType = 1 indicates that the node is an element node, not a text node.
4 // perform some operations
5}
6}
Obtain the child nodes of an element and its child nodes:
1 var ul = document. getElementById ("myList ");
2 var items = ul. getElementsByTagName ("li"); // li in li will also be obtained
From Sunday walk