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

var x=document.getElementsByTagName("p");

These nodes can be accessed by index number. To access the second <p>, you can write:

y=x[1];

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

x=document.getElementsByTagName("p"); for (i=0;i<x.length;i++) { document.write(x[i].innerHTML); document.write("<br>"); }

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:

<html> <head> <meta charset="utf-8"> </head> <body> <p>Hello World!</p> <div> <p>DOM is very useful!</p> <p>This example demonstrates the relationships between nodes.</p> </div> </body> </html>
  • 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

<p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script>

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

<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>

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

<p id="intro">Hello World!</p> <script> txt=document.getElementById("intro").childNodes[0].nodeValue; document.write(txt); </script>

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