HTML DOM Navigation
With HTML DOM, you can navigate the node tree using node relationships.
HTML DOM Node List
The getElementsByTagName() method returnsa node list. A node list is an array of nodes.
The following code selects all <p> nodes in the document:
Example
These nodes can be accessed by index number. To access the second <p>, you can write:
Try it yourself »
Note:
The index starts at 0.
HTML DOM Node List Length
The length property defines the number of nodes in a node list.
You can use the length property to loop through the node list:
Example
Try it yourself »
Example analysis:
- Get all <p> element nodes
- Output the value of the text node of each <p> element
Navigating Node Relationships
You can navigate in the document structure using three node properties: parentNode, firstChild, and lastChild.
Look at the following HTML snippet:
- 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 parent node (parentNode) of the first <p> element and the <div> element
The firstChild property can be used to access an element's text:
Example
Try it yourself »
DOM Root Nodes
There are two special properties that allow access to the full document:
- document.documentElement - Full document
- document.body - The body of the document
Example
Try it yourself »
childNodes and nodeValue
In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following code gets the value of the <p> element with id="intro":
Example
Try it yourself »
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial, we will use the innerHTML property. However, learning the above methods helps with understanding the DOM tree structure and navigation.
Other Extensions