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.
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");
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";
});
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) |
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.
querySelectorAll() is the most common way to get onequerySelectorAll are staticchildNodes returns a live NodeListforEach() in modern
browserslength property is always available for loops