Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.2 — Selecting Elements
JavaScript · Example 2 of 3

Live HTMLCollection versus static NodeList

After adding "C", the live collection and children both count 3, but the snapshot from querySelectorAll still has 2. Array.from turns any list into a real array with map.

Before you can change an element you must find it: getElementById finds one by id, querySelector and querySelectorAll find elements with any CSS selector, and closest searches upwards; knowing which return live collections and which return null prevents most DOM bugs.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given a list of products where some have class sale, log how many are on sale and the text of the first one, using one selector per lookup.

02

Given <button class="remove"> inside <li class="task" data-id="7">, write a function taskIdOf(button) that returns the task's data-id attribute using closest.

03

Turn all .price elements into an array of numbers and log their total.

Explain it without notes

01

Compare getElementById, querySelector and querySelectorAll: arguments, return values and what happens when nothing matches.

02

What is the difference between a NodeList and an HTMLCollection, and between live and static lists?

03

What does element.closest(selector) do, and when would you use it?

04

Why can removing classes inside a loop over getElementsByClassName skip elements? How do you avoid it?

Live HTMLCollection versus static NodeList

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

2 2
2 3 3
true true
function undefined
[ 'A', 'B', 'C' ]