JavaScript HTML DOM Node Lists
The HTML DOM NodeList Object
A NodeList object is a collection of nodes extracted from a document. It is similar to an HTMLCollection object.
- Some older browsers return a NodeList object instead of an HTMLCollection for methods like getElementsByClassName().
- All browsers return a NodeList object for the childNodes property.
- Most browsers return a NodeList object for the querySelectorAll() method.
Example: Selecting All <p> Nodes
const myNodeList = document.querySelectorAll("p");The elements in the NodeList can be accessed by an index number. To access the second <p> node, you can write:myNodeList[1];
Note: The index starts at 0.
NodeList Length
The length property defines the number of nodes in a NodeList:
Example:
myNodeList.length;The length property is useful when you want to loop through the nodes in a NodeList:Example: Changing the Color of All <p> Elements in a NodeListconst myNodeList = document.querySelectorAll("p");for (let i = 0; i < myNodeList.length; i++) { myNodeList[i].style.color = "red";}
The Difference Between an HTMLCollection and a NodeList
A NodeList and an HTMLCollection are similar:
- Both are array-like collections (lists) of nodes (elements) extracted from a document.
- Both can be accessed by index numbers (starting at 0).
- Both have a length property that returns the number of elements in the list.
HTMLCollection:
- A collection of document elements.
- Items can be accessed by their name, id, or index number.
- Always a live collection (e.g., if you add an <li> element to a list in the DOM, the list in the HTMLCollection will also change).
NodeList:
- A collection of document nodes (element nodes, attribute nodes, and text nodes).
- Items can only be accessed by their index number.
- Most often a static collection (e.g., if you add an <li> element to a list in the DOM, the list in NodeList will not change).
Method Returns:
- getElementsByClassName() and getElementsByTagName() return a live HTMLCollection.
- querySelectorAll() returns a static NodeList.
- childNodes property returns a live NodeList.
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 by index. However, you cannot use Array methods like push(), pop(), or join() on a NodeList.