JavaScript HTML DOM Node List

NodeList object is a list (collection) of nodes obtained from a document.

NodeList objects are similar to HTMLCollection objects.

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

The childNodes property of all browsers returns a NodeList object.

querySelectorAll () for most browsers returns a NodeList object.

The following code selects all <p> nodeļ¼š


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

Elements in a NodeList can be accessed by index (starting at 0). Accessing the second "p" element can be the following:

y = myNodeList[1];
Try it Yourself »

HTML DOM Node List Length

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


var myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;
Try it Yourself »

Instance analysis

Get <p> Collection of elements:

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

Number of elements in the node list:

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

length attribute is often used to traverse a list of nodes.

Try it Yourself »

Difference between HTMLCollection and NodeList

HTMLCollection is a collection of HTML elements.

NodeList is a collection of document nodes.

NodeList has many similarities to HTMLCollection.

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

NodeList and HTMLCollection both have a length property.

The HTMLCollection element can be obtained by name, id, or index.

NodeList can only be obtained by index.

Only NodeList objects have attribute nodes and text nodes.

The list of nodes is not an array!

The list of nodes may look like an array, but it's not.

You can use the index to get elements like an array.

A list method cannot use an array: valueOf (), pop (), push (), Or join ().