Dom Collections in JavaScript
? DOM Collections in JavaScript
What Are DOM Collections?
DOM Collections are array-like objects returned by various DOM methods that represent groups of elements or nodes in a document. Unlike regular arrays, they often have limited methods but can be iterated similarly.
Common DOM Collections
| Collection Type | Returned By | Description |
|---|---|---|
| HTMLCollection | document.getElementsByTagName(), document.getElementsByClassName(), element.children | Live collection of elements matching criteria |
| NodeList | document.querySelectorAll(), childNodes | Static (or live in some cases) list of nodes |
| NamedNodeMap | element.attributes | Collection of attributes of an element |
1. HTMLCollection
Live collection — updates automatically when the DOM changes
Contains only element nodes (no text or comment nodes)
Common methods:
.item(index),.namedItem(name), and can be accessed by index[0]
const divs = document.getElementsByTagName("div");console.log(divs.length);console.log(divs[0].innerText);2. NodeList
Can be static or live (most modern ones like
querySelectorAllare static)Contains any type of node (elements, text, comments)
Has
.forEach()method, but not all Array methodsCan be converted to an array using
Array.from()or spread[...nodeList]
const nodes = document.querySelectorAll(".item");nodes.forEach(node => { console.log(node.textContent);});3. NamedNodeMap
Collection of attributes of an element
Access by index or attribute name
const attrs = document.querySelector("img").attributes;console.log(attrs.length);console.log(attrs["src"].value);Differences Summary
| Feature | HTMLCollection | NodeList |
|---|---|---|
| Live vs Static | Live | Usually static (except childNodes) |
| Contains | Elements only | Any node type |
| Methods | Limited | Has .forEach() |
| Conversion | Can be converted to Array | Can be converted to Array |
Example: Looping Through a Collection
const elements = document.getElementsByClassName("box");// Using for loop (works for both HTMLCollection and NodeList)for (let i = 0; i < elements.length; i++) { elements[i].style.backgroundColor = "lightblue";}// Using forEach (works only on NodeList)const nodeList = document.querySelectorAll(".box");nodeList.forEach(el => el.style.border = "1px solid red");Would you like me to show examples of converting collections to arrays or best practices for manipulating DOM collections?