JavaScript HTML DOM Node Lists
14 April 2025 | Category: JavaScript
When you use certain DOM methods like querySelectorAll()
or access properties like childNodes
, JavaScript gives you a NodeList.
A NodeList is a collection of DOM nodes, and understanding how it works is key to manipulating the DOM effectively.
đ¸ What is a NodeList?
A NodeList is an array-like object containing a list of nodes (elements, text, comments, etc.). It can be:
- Static (not live) â doesn’t update automatically when the DOM changes
- Live â updates in real-time when the DOM is modified
đ§Ş How Do You Get a NodeList?
â
Using document.querySelectorAll()
Returns a static NodeList
<p>First</p>
<p>Second</p>
<script>
const paras = document.querySelectorAll("p");
console.log(paras); // NodeList of 2 <p> elements
</script>
â
Using childNodes
Returns a live NodeList including text nodes, comments, etc.
<div id="container">
Hello
<span>World</span>
</div>
<script>
const container = document.getElementById("container");
const nodes = container.childNodes;
console.log(nodes); // Includes text node + span
</script>
â NodeList vs HTMLCollection
Feature | NodeList | HTMLCollection |
---|---|---|
Type of items | Any node (element, text) | Only elements |
Supports forEach() | â Yes | â No (unless converted) |
Live updates | â Usually static | â Often live |
How to get it | querySelectorAll() | getElementsByClassName() |
đ Looping Through a NodeList
â
Using forEach()
const items = document.querySelectorAll(".item");
items.forEach((el) => {
el.style.color = "blue";
});
â
Using for...of
for (let el of items) {
console.log(el.textContent);
}
â
Using traditional for
loop
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
đ Live vs Static NodeList Example
<ul id="list">
<li>One</li>
</ul>
<button onclick="addItem()">Add Item</button>
<script>
const nodeList = document.querySelectorAll("li"); // Static
const liveList = document.getElementsByTagName("li"); // Live
function addItem() {
const li = document.createElement("li");
li.textContent = "New Item";
document.getElementById("list").appendChild(li);
console.log("Static NodeList length:", nodeList.length); // Wonât change
console.log("Live HTMLCollection length:", liveList.length); // Will update
}
</script>
đ§ Accessing Nodes from a NodeList
const listItems = document.querySelectorAll("li");
console.log(listItems[0]); // First li
console.log(listItems.item(1)); // Second li using .item()
â Summary
Feature | Description |
---|---|
NodeList type | Array-like list of nodes |
Live/Static | Mostly static (e.g., querySelectorAll ) |
Looping methods | for , forEach() , for...of |
Common methods that return | querySelectorAll() , childNodes |
Convert to array | Array.from(nodeList) |