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

Live vs Static Collections During Traversal

Understanding how DOM changes affect collections while iterating and avoiding common pitfalls.

Live vs Static Collections During Traversal

You'll learn how changes to the DOM while you're looping through a collection can cause unexpected behavior—and how to avoid it.

The Core Problem

When you traverse a collection of DOM elements (like the result of getElementsByClassName() or childNodes), you need to know if that collection is live or static.

A live collection updates automatically when the DOM changes. If you're looping through it and remove an element, the collection shrinks immediately—even mid-loop. This can cause you to skip elements or loop forever.

A static collection (like those from querySelectorAll()) takes a snapshot at the moment you create it. Changes to the DOM afterward don't affect what you're iterating over.

The Classic Pitfall

Imagine removing items from a live collection while looping forward:

const items = document.getElementsByClassName('item'); // Live!

for (let i = 0; i < items.length; i++) {
  items[i].remove(); // Removes element, collection shrinks
  // Now items[1] becomes items[0]—you skip every other element!
}

Safe Traversal Strategies

Option 1: Loop backward through live collections:

for (let i = items.length - 1; i >= 0; i--) {
  items[i].remove(); // Safe: removing from the end
}

Option 2: Convert to static array:

const itemsArray = Array.from(items);
itemsArray.forEach(item => item.remove());

Option 3: Use static collections:

const items = document.querySelectorAll('.item'); // Static snapshot

Key Takeaway: Live collections update during traversal; always loop backward, convert to an array, or use static methods like querySelectorAll() when modifying the DOM during iteration.