HTML DOM Navigation
Through the HTML DOM, you can navigate the node tree using node relationships.
HTML DOM Node List
The getElementsByTagName()
method returns a node list. A node list is an array of nodes.
The following code selects all <p>
nodes in the document:
Example
var x = document.getElementsByTagName("p");
You can access these nodes by their index number. To access the second <p>
, you can write:
y = x[1];
Note:
Index numbers start at 0.
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 the node list:
Example
x = document.getElementsByTagName("p");
for (i = 0; i < x.length; i++) {
document.write(x[i].innerHTML);
document.write("<br>");
}
Example Explanation:
- Get all
<p>
element nodes - Output the value of the text node of each
<p>
element
Navigating Node Relationships
You can use three node properties: parentNode
, firstChild
, and lastChild
to navigate the document structure.
Consider the following HTML snippet:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>Hello World!</p>
<div>
<p>DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
- The first
<p>
element is the first child of the<body>
element (firstChild
) - The
<div>
element is the last child of the<body>
element (lastChild
) - The
<body>
element is the parent node of the first<p>
and<div>
elements (parentNode
)
The firstChild
property can be used to access the text of an element:
Example
<p id="intro">Hello World!</p>
<script>
x = document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
DOM Root Nodes
There are two special properties that allow access to the entire document:
document.documentElement
- the entire documentdocument.body
- the body of the document
Example
<p>Hello World!</p>
<div>
<p>DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
childNodes
and nodeValue
Besides the innerHTML
property, you can also use the childNodes
and nodeValue
properties to get the content of an element.
The following code retrieves the value of the <p>
element with id="intro":
Example
<p id="intro">Hello World!</p>
<script>
txt = document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
In the above example, 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 in understanding the DOM tree structure and navigation.