HTML DOM Navigation


With the HTML DOM, you can use node relationships to navigate the node tree.


HTML DOM node list

getElementsByTagName() method returns a list of nodes . 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 subscript numbers. To access the second <p>, you can write:

y=x[1];

Try It! 

Notice:

Subscript 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 list of nodes:

Example

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

 Try It! 

Example analysis:

  • Get all <p> element nodes

  • Output the value of the text node of each <p> element


Navigate Nodes

You can navigate the document structure using three node properties: parentNode, firstChild, and lastChild.

See 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 relationship of nodes.</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 parentNode of the first <p> and <div> elements

The firstChild property can be used to access the element's text:

Example

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

Try It! 


DOM root node

There are two special properties that give access to the full documentation:

  • document.documentElement - All documents

  • document.body - The body of the document

Example

<p>Hello World!</p>
<div>
    <p>DOM is very useful!</p>
    <p>This example demonstrates </b>document.body<b> property.</p>
</div>
 
<script>
    alert(document.body.innerHTML);
</script>

  Try It! 


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! 

In the above example, getElementById is a method and childNodes and nodeValue are properties.

In this tutorial, we will use the innerHTML attribute. However, learning the above method helps to understand the DOM tree structure and navigation.