Dom Node Lists in JavaScript
? DOM Node Lists in JavaScript
What is a NodeList?
A NodeList is a collection (like an array) of nodes returned by some DOM methods.
It represents a list of nodes (elements, text nodes, etc.) in document order.
Unlike arrays, NodeLists have limited methods but can be iterated.
How to Get a NodeList?
Common DOM methods returning a NodeList:
document.querySelectorAll(selector)element.childNodes
NodeList vs HTMLCollection
| Feature | NodeList | HTMLCollection |
|---|---|---|
| Can include | Any node type (elements, text, etc) | Only element nodes |
| Returned by | querySelectorAll(), childNodes | children, getElementsByTagName |
| Iterable | Yes (can use forEach) | Yes (but older browsers lack forEach) |
| Live (auto-update) | Usually static (does not update automatically) | Usually live (updates with DOM) |
Example: Using NodeList from querySelectorAll
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li></ul><script>const items = document.querySelectorAll("li");// NodeList supports forEachitems.forEach((item, index) => { console.log(`Item ${index + 1}: ${item.textContent}`);});</script>Iterating Over a NodeList
Using forEach
nodeList.forEach(node => { console.log(node);});Using for Loop
for (let i = 0; i < nodeList.length; i++) { console.log(nodeList[i]);}Using for...of Loop (ES6+)
for (const node of nodeList) { console.log(node);}Converting NodeList to Array
To use array methods like .map(), .filter(), convert NodeList:
const nodeArray = Array.from(nodeList);// orconst nodeArray = [...nodeList];Summary
| Property / Method | Description |
|---|---|
document.querySelectorAll() | Returns a static NodeList of matched nodes |
element.childNodes | Returns all child nodes (including text) |
.forEach() | Iterate over NodeList directly |
Array.from() | Convert NodeList to Array |
Want me to show how to filter NodeList by some criteria or manipulate NodeList items dynamically?