Latest web development tutorials

HTML DOM navigation

Through the HTML DOM, you are able to use the node in the node navigation tree relationship.


HTML DOM node list

getElementsByTagName () method returns a list of nodes. Node list is a node array.

The following code selected document all <p> node:

Examples

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

It can be accessed by the next label. To access the second <p>, you can write:

y=x[1];

try it"

note:

Under the label starts at 0.


HTML DOM Node List Length

length attribute defines the number of nodes in the node list.

You can use the length property to loop node list:

Examples

x=document.getElementsByTagName("p");

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

try it"

Analysis examples:

  • Get all <p> element node
  • The output value of each <p> element of the text node

Navigation node relationship

You can use three node attributes: parentNode, firstChild and lastChild, navigate through the document structure.

Consider the following HTML fragment:

<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 <p> element is the first child of the <body> element (firstChild)
  • <Div> element is the last child element <body> element (lastChild)
  • <Body> element is the first <p> element and a <div> element's parent node (parentNode)

firstChild property can be used to access elements of the text:

Examples

<html>
<body>

<p id="intro">Hello World!</p>

<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>

</body>
</html>

try it"


DOM root node

There are two special attributes, you can access all of the documentation:

  • document.documentElement - all documents
  • document.body - body of the document

Examples

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


childNodes and nodeValue

In addition to innerHTML property, you can also use the childNodes and nodeValue property to get the content of the element.

The following code gets the id = "intro" the <p> element values:

Examples

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

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

In this tutorial, we will use the innerHTML property. However, the above learning method helps to navigate the DOM tree structure and understanding.