Finding Elements

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 1

The Live Collection Trap

See why iterating a live HTMLCollection while mutating the DOM skips elements, and how querySelectorAll's static NodeList fixes it.

The Live Collection Trap

getElementsByClassName returns a live collection. When you remove elements while iterating, the collection shrinks under you and indices shift. Items get skipped silently.

// Returns a live HTMLCollection
const items = container.getElementsByClassName('menu-item');

for (let i = 0; i < items.length; i++) {
  items[i].remove(); // Collection shrinks!
  // i increments, next element is now at i → skipped
}
Menu Items
Espresso
Latte
Cappuccino
Americano
Practice: Finding Elements — Interactive Exercises | Durgesh Rai