JavaScript HTML DOM Node Lists


The HTML DOM NodeList Object

A NodeList is like a collection of nodes that are taken from a document.

ANodeList object is quite similar to an HTMLCollection object.

Some older web browsers might give you a NodeList instead of an HTMLCollection when you use methods like getElementsByClassName().

Every web browser provides a NodeList object when accessing the childNodes property.

Many browsers provide a NodeList object when you use the querySelectorAll() method.

The code below chooses all <p> elements in a document:

Note: The counting begins from zero.


HTML DOM Node List Length

The length property tells us how many nodes are in a node list.

The length property comes in handy when you need to go through the nodes in a node list.


The Difference Between an HTMLCollection and a NodeList

A NodeList and an HTML collection are quite similar.

Both are lists of elements taken from a document. You can find the elements in these lists using index numbers, starting from 0.

Both come with a length attribute that shows how many items are in the list or collection.

An HTMLCollection is a group of elements in a document.

A NodeList is a group of document nodes, including element nodes, attribute nodes, and text nodes.

You can get HTMLCollection items using their name, id, or index number.

You can only get to NodeList items using their index number.

An HTMLCollection is like a group of things that is always live or active. For instance, if you put a new <li> element into a list in the DOM (Document Object Model), the list in the HTMLCollection will automatically update to include the new element.

A NodeList is usually a static collection. For instance, if you insert an <li> element into a DOM list, the NodeList for that list will remain unchanged.

The getElementsByClassName() and getElementsByTagName() functions give back a dynamic HTMLCollection.

The querySelectorAll() function gives back a fixed NodeList.

The childNodes property gives back a dynamic list of nodes.


Not an Array!

A NodeList might seem similar to an array, but it's not.

You can go through a group of nodes and access each node using its index.

However, you can't apply Array functions such as push(), pop(), or join() to a NodeList.