HTML DOM NodeList
NodeList
A NodeList is an array-like collection (list) of Node Objects.
The nodes in a NodeList can be accessed by index (starts at 0).
The length property returns the number of nodes in a NodeList.
NodeList vs. HTMLCollection
A NodeList is almost the same as anHTMLCollection.
See the description below.
Who Returns a NodeList?
Properties and Methods
The following properties and methods can be used on a NodeList:
| Name | Description |
|---|---|
| entries() | Returns an Iterator with the key/value pairs from the list |
| forEach() | Executes a callback function for each node in the list |
| item() | Returns the node at a specified index |
| keys() | Returns an Iterator with the keys from the list |
| length | Returns the number of nodes in a NodeList |
| values() | Returns an Iterator with the values from the list |
Example
Select all<p> nodes in a document:
The elements in the NodeList can be accessed by an index number.
To access the second <p> node you can write:
Note: The index starts at 0.
HTML DOM Node List Length
Thelength property defines the number of nodes in a node list:
Thelength property is useful when you want to loop through the nodes in a node list:
Example
Change the color of all <p> elements in a node list:
for (let i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.color = "red";
}
Not an Array
A NodeList is not an Array!
A NodeList may look like an array, but it is not.
You can loop through a NodeList and refer to its nodes with an index.
But you cannot use Array methods like push(), pop(), or join() on a NodeList.
The Difference Between an HTMLCollection and a NodeList
ANodeList and anHTMLcollection is very much the same thing.
Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.
Both have alength property that returns the number of elements in the list (collection).
An HTMLCollection is a collection ofdocument elements.
A NodeList is a collection ofdocument nodes (element nodes, attribute nodes, and text nodes).
HTMLCollection items can be accessed by their name, id, or index number.
NodeList items can only be accessed by their index number.
An HTMLCollection is always alive collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
A NodeList is most often astatic collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change.
ThegetElementsByClassName() andgetElementsByTagName()methods return a live HTMLCollection.
ThequerySelectorAll() method returns a static NodeList.
ThechildNodes property returns a live NodeList.
Live NodeList
In some cases, the NodeList islive: A change in the DOM updates the NodeList.
ThechildNodes method returns a live NodeList.

