JavaScript HTML DOM Node List

HTML DOM NodeList object

NodeList An object is a node list (collection) extracted from the document.

NodeList objects are almost the same as HTMLCollection objects.

If using getElementsByClassName() method, some (old) browsers will return NodeList object instead of HTMLCollection.

All browsers will return childNodes attribute returns a NodeList object.

Most browsers will return querySelectorAll() The method returns a NodeList object.

The following code selects all <p> nodes in the document:

Example

var myNodeList = document.querySelectorAll("p");

Try It Yourself

Elements in NodeList can be accessed by index number.

To access the second <p> node, you can write as follows:

y = myNodeList[1];

Note:The index starts from 0.

HTML DOM Node List Length

length The attribute defines the number of nodes in the node list:

Example

var myNodelist = document.querySelectorAll("p");
document.getElementById("demo").innerHTML = myNodelist.length;

Try It Yourself

Example explanation:

  • Create a list of all <p> elements
  • Display the length of this list

length The attribute is very useful when you want to iterate through nodes in the node list:

Example

Change the background color of all <p> elements in the node list:

var myNodelist = document.querySelectorAll("p");
var i;
for (i = 0; i < myNodelist.length; i++) {
    myNodelist[i].style.backgroundColor = "red";
}

Try It Yourself

Difference between HTMLCollection and NodeList

HTMLCollection (previous chapter) is a collection of HTML elements.

NodeList is a collection of document nodes.

NodeList and HTML collections are almost identical.

HTMLCollection and NodeList objects are class array object lists (collections).

They all have a defined list (collection) of item numbers length Properties.

They can all be accessed like an array through an index (0, 1, 2, 3, 4, ...).

Access HTMLCollection items can be through their name, id, or index number.

Access NodeList items can only be through their index number.

Only NodeList objects can contain attribute nodes and text nodes.

The node list is not an array!

The node array looks like an array, but it is not.

You can traverse the node list and refer to its nodes as if they were an array.

However, you cannot use array methods on node lists, such as valueOf(),push(),pop() or join().