HTML DOM
navigation
With HTML DOM, you can use node relationships to navigate through the node tree.
A list of HTML DOM nodes
The getElementsByTagName() method returns a list
of nodes.
The list of nodes is an array of nodes.
The following code picks out all the nodes in the document and writes the code with a single click:
var x=document.getElementsByTagName("p");
These nodes can be accessed by a lower sign.
To access the second , you can write this:
y=x[1];
Try it out . . .
It is important to note that:
The underse mark starts at 0.
The length of the LIST of HTML DOM nodes
The length property defines the number of nodes in the node list.
You can use the length property to loop the list of nodes:
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
Try it out . . .
Instance resolution:
-
Gets all the element nodes
-
Outputs the value of the text node for each of the elements
The navigation node relationship
You can navigate through the document structure using three node properties: parentNode, firstChild, and lastChild.
Take a look at the HTML fragment below:
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
-
The
first element
is the first
child element of the element (firstChild)
-
The element is
the last child of the element (lastChild)
-
The element is the parent Node of the first element and the element
The firstChild property can be used to access the text of an element:
<html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
Try it out . . .
The DOM root node
There are two special properties that have access to all documents:
-
document.documentElement - All documents
-
document.body - the body of the document
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
Try it out . . .
childNodes and nodeValue
In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the contents of the element.
The following code will teach you how to get the value of the element of id"intro":
<html>
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
Try it out . . .
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial, we'll use the innerHTML property.
However, learning the above approach helps you understand the doM tree structure and navigation.
Related articles
CSS navigation bar