← Back to Chapters

JavaScript DOM Collections

? JavaScript DOM Collections

⚡ Quick Overview

DOM Collections are array-like objects that group multiple DOM nodes together. They are returned by many DOM methods when you select more than one element, and they let you read, loop over, and update groups of elements in one go.

  • HTMLCollection – live collection of element nodes.
  • NodeList – list of nodes (can be live or static).
  • Collections are array-like (have length and index access) but are not real arrays.

? Key Concepts

  • HTMLCollection is returned by methods like getElementsByTagName() and getElementsByClassName().
  • NodeList is returned by methods like querySelectorAll() and childNodes.
  • Live collections auto-update when the DOM changes.
  • Static collections stay fixed even if the DOM updates.
  • Use Array.from() or [...collection] to convert collections into real arrays.

? Syntax and Theory

Common DOM Collection sources:

  • document.getElementsByTagName("div")HTMLCollection (live)
  • document.getElementsByClassName("item")HTMLCollection (live)
  • element.childrenHTMLCollection (live)
  • document.querySelectorAll("p")NodeList (static)
  • element.childNodesNodeList (often live, includes text nodes)

Access patterns:

  • collection[index] → returns the node at a position.
  • collection.item(index) → same as bracket access.
  • collection.length → number of nodes.
  • for loop or forEach() (for NodeList) for iteration.

? Code Examples

? HTMLCollection in Action

This example selects all elements with the class item and shows how many were found and the text of the first one.

? View Code Example
<div class="item">One</div>
<div class="item">Two</div>

<script>
const items = document.getElementsByClassName("item");
console.log(items.length);       // 2
console.log(items[0].innerText); // One
</script>

? NodeList with querySelectorAll()

querySelectorAll() returns a static NodeList. You can use forEach() to loop over it directly.

? View Code Example
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>

<script>
const fruits = document.querySelectorAll("li");
fruits.forEach(fruit => console.log(fruit.textContent));
</script>

? Live vs Static Collections

Here, a new list item is added after both collections are created. The live collection updates automatically, the static one does not.

? View Code Example
<ul id="menu"><li>A</li></ul>

<script>
const liveList = document.getElementsByTagName("li"); // live
const staticList = document.querySelectorAll("li");   // static

document.getElementById("menu")
.appendChild(document.createElement("li")).textContent = "B";

console.log(liveList.length);   // 2
console.log(staticList.length); // still 1
</script>

? Accessing Items by Index

You can use both bracket notation and the item() method to access elements in a collection.

? View Code Example
<script>
const divs = document.getElementsByTagName("div");
console.log(divs[1]);      // via index
console.log(divs.item(1)); // via item() method
</script>

? Looping Through Collections

HTMLCollections need classic loops, while NodeLists support forEach() directly.

? View Code Example
<script>
const divs = document.getElementsByTagName("div");
for (let i = 0; i < divs.length; i++) {
console.log(divs[i].textContent);
}

const paras = document.querySelectorAll("p");
paras.forEach(p => p.style.color = "blue");
</script>

? Converting Collections to Arrays

To use array methods like map() or filter(), first convert the collection to a real array.

? View Code Example
<script>
const coll = document.getElementsByClassName("item");
const arr1 = Array.from(coll);
const arr2 = [...coll];

arr1.forEach(el => el.style.color = "green");
</script>

? Output and Behavior

? What You’ll See

  • For the HTMLCollection example, the console logs the number of elements and the text of the first one.
  • For the NodeList example, each list item’s text (like Apple, Banana) is printed in the console.
  • In the live vs static example:
    • liveList.length becomes 2 after adding a new <li>.
    • staticList.length remains 1, showing that it is static.
  • Looping examples print text content of each node and apply styles (like blue text) to matching elements.

?️ Summary Table of Common Methods

Method / Property Type Returned Live?
getElementsByTagName HTMLCollection Yes
getElementsByClassName HTMLCollection Yes
children HTMLCollection Yes
querySelectorAll NodeList No (static)
childNodes NodeList Yes (often live)

? Helpful Tips

  • forEach() works directly on NodeList (e.g., from querySelectorAll()).
  • Convert HTMLCollections to arrays using Array.from() or [...collection] before using methods like map() or filter().
  • Use the length property to check how many elements your selection returned.
  • Access items using both collection[index] and collection.item(index).
  • Prefer querySelectorAll() for flexible CSS selector-based queries (even though it returns a static list).
  • Use live collections when you specifically want automatic updates as the DOM changes.

? Practice Exercises

  • Create several <div class="box"> elements and use getElementsByClassName("box") to change all of them to red.
  • Append a new list item to a <ul> and log the length of a live collection and a static NodeList to see the difference.
  • Use childNodes to loop through all nodes and print only element nodes (skip text nodes using node.nodeType === 1).
  • Use querySelectorAll() to get a NodeList, convert it to an array, and reverse the order of items using JavaScript.
  • Experiment with both collection[index] and collection.item(index) to access elements and compare their behavior.