HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM NodeLists

A NodeList is a collection of nodes extracted from a document. It is very similar to an HTMLCollection, but there are vital differences in how they behave and what they contain.


Getting a NodeList

Commonly, you get a NodeList in two ways:

  • querySelectorAll(): Returns a static NodeList.
  • childNodes: A property that returns a live NodeList.
const list = document.querySelectorAll("p");

Accessing and Iterating

Like collections, you use indices and the length property. However, modern NodeLists often support the forEach() method directly!

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

myNodeList.forEach(node => {
  node.style.backgroundColor = "lightgrey";
});

The Difference: NodeList vs. HTMLCollection

While they look identical, they have different structural definitions:

Feature HTMLCollection NodeList
Contains Only Element Nodes Any Node (Text, Commments, Elements)
Accessed By Name, ID, or Index Only by Index
Live Status Always Live Usually Static (if from querySelector)
Important Distinction: A static NodeList (from querySelectorAll) is a snapshot. If you add more elements to the page, the list does not update. You must call the selector again to get the new items.

Key Points to Remember

  • NodeList can contain any type of document node
  • querySelectorAll() is the most common way to get one
  • Unlike HTMLCollection, NodeLists from querySelectorAll are static
  • childNodes returns a live NodeList
  • Iterate through NodeLists using forEach() in modern browsers
  • Neither NodeList nor HTMLCollection are real arrays
  • The length property is always available for loops