Easy Tutorial
❮ Js Function Parameters Js Objects ❯

JavaScript HTML DOM NodeList

The NodeList object is a collection of nodes retrieved from the document.

The NodeList object is similar to the HTMLCollection object.

Some older browsers' methods (such as getElementsByClassName()) return a NodeList object instead of an HTMLCollection object.

The childNodes property of all browsers returns a NodeList object.

Most browsers' querySelectorAll() method returns a NodeList object.

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

Example

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

Elements in a NodeList can be accessed by their index (starting from 0).

To access the second <p> element, you can use the following code:

y = myNodeList[1];

NodeList Object Length Property

The length property of the NodeList object defines the number of elements in the node list.

Example

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

Example Explained

Retrieve the collection of <p> elements:

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

Display the number of elements in the node list:

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

The length property is often used to iterate through 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";
}

Difference Between HTMLCollection and NodeList

An HTMLCollection is a collection of HTML elements.

A NodeList is a collection of document nodes.

Both NodeList and HTMLCollection have many similarities.

Both NodeList and HTMLCollection are somewhat similar to array objects and can use indexes (0, 1, 2, 3, 4, ...) to access elements.

Both NodeList and HTMLCollection have a length property.

HTMLCollection elements can be accessed by name, id, or index.

NodeList elements can only be accessed by index.

Only NodeList objects contain attribute nodes and text nodes.

Note: NodeList is not an array!

A NodeList may look like an array, but it is not.

You can access elements with an index, just like with arrays.

However, NodeLists cannot use array methods like valueOf(), pop(), push(), or join().

❮ Js Function Parameters Js Objects ❯