With the HTML DOM, you can navigate through the node tree using node relationships.
1.HTML DOM Node list
The getElementsByTagName () method returns a list of nodes . The node list is an array of nodes.
The following code selects all the <p> nodes in the document:
1 <body> 2 3 <p>hello world!</p> 4 <p>the DOM is very useful! </p> 5 <p>the DOM!</p> 6 <script> 7 x= document.getElementsByTagName ("P"); 8 document.write ("The InnerHTML of the second paragraph is:" + x[2].innerhtml); 9 </script>ten </body>
?? Note: The following label starts from 0.
2.HTML DOM Node list length
The Length property defines the number of nodes in the node list.
You can use the Length property to loop through a list of nodes:
1 x=document.getelementsbytagname ("P"); 2 3 for (i=0;i<x.length;i++) 4 {5document.write (x[i].innerhtml); 6 document.write ("<br/>"); 7 }
navigation node Relationships
You can use three node properties: ParentNode, FirstChild, and LastChild to navigate through the document structure.
Take a look at the following HTML snippet:
1 2 <body> 3 4 <p>hello world!</p> 5 < Div> 6 <p>the DOM is very useful!</p> 7 <p>this example demonstrates Node relationships.</p> 8 </div> 9 </body> >
- The first <p> element is the first child element of the <body> element (FirstChild)
- The <div> element is the last child element of the <body> element (LastChild)
- The <body> element is the first parent node of the <p> element and <div> element (parentnode)
The FirstChild property can be used to access the text of an element:
1 2 <body> 3 4 <p id= "Intro" >hello world!</p> 5< /c4> 6 <script> 7 X=document.getelementbyid ("Intro"); 8 document.write (x.firstchild.nodevalue); 9 </script> </body>
DOM root node
Here are two special properties that can be accessed in all documents:
- Document.documentelement-All Documents
- Document.body-Body of the document
1 2 <body> 3 4 <p>hello world!</p> 5 <div> 6 <p>the DOM is very useful!</p> 7 <p>this example demonstrates the <b>document.body</b> Property.</p> 8 </div> 9 10 <script >11 alert (Document.body.innerHTML); 12 </script>14 </body>15
ChildNodes and NodeValueIn addition to the InnerHTML property, you can also use the ChildNodes and NodeValue properties to get the contents of an element.
The following code gets the value of the <p> element for id= "Intro":
1 2 <body> 3 4 <p id= "Intro" >hello world!</p> 5< /c4> 6 <script> 7var txt=document.getelementbyid ("Intro"). Childnodes[0]. NodeValue; 8 document.write (TXT); 9 </script> </body>
getElementById is a method, while ChildNodes and NodeValue are attributes.
In this tutorial, we will use the InnerHTML property. However, learning the above approach helps to understand the structure and navigation of the DOM tree.
JavaScript Essentials (15) HTML DOM navigation