JavaScript Introduction | Document Object Model | Node List

Node List

A node list is an object returned by the getElementsByTagName() method or by the value of the childNodes property. This object stores all nodes in the document as a list, in the same order as they appear in the HTML document.

Each node in the list can be accessed with an index starting from 0.

// Select all child nodes of the element whose id is "list".
var listItems = document.getElementById("list").childNodes;
// Change the content of the first li element among the child nodes.
listItems[1].firstChild.nodeValue = "Changed the content of the HTML element!";

In the example above, the index 1, not 0, is used when selecting the first <li> element among the child nodes. This is because in the HTML DOM, a separate text node exists after each element node. Therefore, the first node in the child node list of the element whose id is "list" stores the text node that exists after that element.

The following example checks the text nodes that exist between these element nodes.

// Select all child nodes of the element whose id is "list".
var listItems = document.getElementById("list").childNodes;
 
// Print the value of the first child node.
document.write(listItems[0].nodeValue + "<br>");
// Print the value of the first child node of the second child node.
document.write(listItems[1].firstChild.nodeValue + "<br>");
// Print the value of the third child node.
document.write(listItems[2].nodeValue);

The example above shows that another text node exists after each element node. Therefore, when accessing a node list by index, you must keep the existence of these text nodes in mind.

When nodes are added to or removed from a node list object, the object updates its own state information. Therefore, the value of this object’s length property always represents the total number of nodes stored in the node list.

var listItems = document.getElementsByTagName("li");              // Select all <li> elements.
document.getElementById("text").innerHTML = 
"The length of this node list is " + listItems.length + ".<br>"; // Return the number of all child nodes.
function changeTextColor() {
    for (var i = 0; i < listItems.length; i++) {
        listItems[i].style.color = "orange";                      // Change the text color of all child nodes.
    }
}