NodeList Object


JavaScript HTML DOM node list

The NodeList object is a node list (collection) obtained from the document.

The NodeList object is similar to the HTMLCollection object.

Some methods in older browsers (such as getElementsByClassName() ) return NodeList objects instead of HTMLCollection objects.

The childNodes property of all browsers returns a NodeList object.

The querySelectorAll() of most browsers returns a NodeList object.

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

Example

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

The elements in NodeList can be accessed by index (starting with 0).

Access to the second <p> element can be the following code:

y = myNodeList[1];

Try It! 


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;

 Try It! 

Example analysis

Get 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 traverse the list of nodes.

Example

Modify 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! 


The difference between HTMLCollection and NodeList

HTMLCollection is a collection of HTML elements.

NodeList is a collection of document nodes.

NodeList has many similarities with HTMLCollection.

Both NodeList and HTMLCollection are similar to array objects. You can use index (0, 1, 2, 3, 4, ...) to get elements.

Both NodeList and HTMLCollection have length attributes.

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

The NodeList can only be obtained by index.

Only the NodeList object has attribute nodes and text nodes.

The node list is not an array!

The node list may look like an array, but it is not.

You can use index to get elements like an array.

The node list cannot use the array methods: valueOf(), pop(), push(), or join().