From (Copyright Refsnes Data)

HTML DOM Access Nodes

previous next

With the DOM, you can access every node in an HTML document.

Accessing Nodes

You can access a node in three ways:

1. By using the getElementById() method

2. By using the getElementsByTagName() method

3. By navigating the node tree, using the node relationships.

The getElementById() Method

The getElementById() method returns the element with the specified ID:



Try it yourself.

Note: The getElementById() method doesn't work in XML.

The getElementsByTagName() Method

getElementsByTagName() returns all elements with a specified tag name.



Example 1

The following example returns a nodeList of all <p> elements in the document:


Try it yourself.

Example 2

The following example returns a nodeList of all <p> elements that are descendants of the element with id="main":


Try it yourself.

DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of nodes.

The following code stores a list of <p> nodes (a node list) in the variable x:


The <p> elements in x can be accessed by index number. To access the second <p> you can write:


Try it yourself.

Note: The index starts at 0.

You will learn more about node lists in a later chapter of this tutorial.

DOM Node List Length

The length property defines the length of a node list (the number of nodes).

You can loop through a node list by using the length property:

for (i=0;i<x.length;i++)
  document.write("<br />");

Example explained:

  1. Get all <p> element nodes
  2. For each <p> element, output the value of its text node

Try it yourself.

Navigating Node Relationships

The three properties parentNode, firstChild, and lastChild follow the document structure and allow short-distance travel in the document.

Look at the following HTML fragment:


<p id="intro">W3Schools example</p>
<div id="main">
<p id="main1">The DOM is very useful</p>
<p id="main2">This example demonstrates <b>node relationships</b></p>


In the HTML code above, the <p id="intro"> is the first child node (firstChild) of the <body> element, and the <div> element is the last child node (lastChild) of the <body> element.

Furthermore, the <body> is the parent (parentNode) of the every <p> element.

The firstChild property can be used to access the text of an element:

var x=document.getElementById("intro");
var text=x.firstChild.nodeValue;

Try it yourself.

Root Nodes

There are two special document properties that allow access to the tags:

The first property returns the root node of the document and exists in all XML and HTML documents.

The second property is a special addition for HTML pages, and gives direct access to the <body> tag.

Try it yourself.

previous next

From (Copyright Refsnes Data)