Course contentsShow
← Web Development
Lesson 680 of 2,98212. The Document Object ModelFree lesson

Live vs Static Collections

Understand the critical difference between HTMLCollections and NodeLists and when each updates.

Live vs Static Collections

You'll learn the crucial difference between collections that auto-update and those that don't—a common source of bugs in DOM manipulation.

The Core Difference

When you select elements from the DOM, you don't always get the same type of collection back. Some collections are live—they automatically update when the document changes. Others are static—they're frozen snapshots that never change after creation.

HTMLCollections: Live and Dynamic

Methods like getElementsByClassName() and getElementsByTagName() return HTMLCollections, which are live. Think of them as a live video feed of the DOM. If elements are added or removed from the document, the collection instantly reflects those changes without you needing to re-query.

const divs = document.getElementsByTagName('div'); // HTMLCollection
console.log(divs.length); // 3

// Add a new div to the page
document.body.appendChild(document.createElement('div'));

console.log(divs.length); // 4 — automatically updated!

NodeLists: It Depends

NodeLists come in two flavors. Those returned by querySelectorAll() are static—they're like a photograph of the DOM at query time. Meanwhile, properties like childNodes return live NodeLists.

const items = document.querySelectorAll('.item'); // Static NodeList
console.log(items.length); // 2

// Add another .item element
document.body.appendChild(newItem);

console.log(items.length); // Still 2 — it doesn't update!

Why This Matters

Live collections can cause unexpected behavior in loops (they grow as you add elements) or make you think your code isn't working. Static collections might seem "stale" if you expect them to update. Knowing which you're working with prevents hours of debugging.

Key Takeaway: HTMLCollections are always live and auto-update; NodeLists from querySelectorAll() are static snapshots, while those from properties like childNodes are live—know which you're using to avoid surprises.