π Letβs break down the difference between HTMLCollection and NodeList in JavaScript DOM:
1. What they are
HTMLCollectionβ A live collection of HTML elements only.NodeListβ A collection of nodes (can be elements, text nodes, comments, etc.).
2. Live vs Static
- HTMLCollection is live β It updates automatically when the DOM changes.
- NodeList can be live or static:
- Returned by
querySelectorAll()β static (doesnβt update if DOM changes). - Returned by
childNodesβ live (updates with DOM changes).
- Returned by
3. Methods available
- HTMLCollection
- Indexed like an array (can access by index).
- Can be accessed by
name,id, orindex. - β No built-in
forEach().
- NodeList
- Indexed like an array.
- β
forEach()is available (on modern browsers). - β No
map,filter,reduce(must convert to array first).
4. How they are obtained
- HTMLCollection comes from:
document.getElementsByTagName()document.getElementsByClassName()document.forms,document.images, etc.
- NodeList comes from:
document.querySelectorAll()(static)node.childNodes(live)
5. Example
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
let htmlCollection = document.getElementsByTagName("li"); // HTMLCollection (live)
let nodeList = document.querySelectorAll("li"); // NodeList (static)
console.log(htmlCollection); // HTMLCollection(2)
console.log(nodeList); // NodeList(2)
// Add a new li
let newLi = document.createElement("li");
newLi.textContent = "Item 3";
document.getElementById("list").appendChild(newLi);
console.log(htmlCollection.length); // 3 (live update)
console.log(nodeList.length); // 2 (static, no update)
</script>
β Summary Table:
| Feature | HTMLCollection | NodeList |
|---|---|---|
| Contains | Only HTML elements | Any node (elements, text, etc.) |
| Live or Static | Always live | Can be live or static |
| Common sources | getElementsBy* | querySelectorAll, childNodes |
| Methods | No forEach | Has forEach (modern browsers) |
| Array methods | β Not available | β Not available (convert first) |
