Faragiri

Learn The DOM JavaScript

Two ways to select the same three elements, and only one of them notices when a fourth arrives. Plus the spread that gives a NodeList the methods it does not have.

4Sections
3Min read
4Depth

Recommended Before This

0 / 2

Two selectors, same three list items, measured in a browser on 2026-09-02.
document.getElementsByClassName('dock') and
document.querySelectorAll('.dock') both report 3. Append a fourth
item to the list and, without re-running either selector, the first reports 4
and the second still reports 3.

The first is a live HTMLCollection, a standing query that keeps matching. The
second is a static NodeList, a snapshot of the document at the moment it ran.
Neither is wrong and the difference is the source of the two classic bugs: a
loop over a live collection that adds matching elements never ends, and a
snapshot held across a re-render silently operates on elements no longer on the
page.

A NodeList is not an array, and the fix is one character

document.querySelectorAll('.dock').constructor.name answers
NodeList, and typeof its map answers
undefined. It has forEach and nothing else from the
array family, which is exactly enough to look like an array until you reach for
filter.

One idiom, two fixes

Turning a NodeList or live collection into a safe array

Spreading querySelectorAll('.dock') into brackets supplies array methods like map and filter while freezing a live collection into a snapshot.

NodeList or HTMLCollectionHas forEach, but typeof map is undefined
  1. 01Three-dot spread [...]Copies matched elements into a real Array instance
  2. 02Enables map and filterReads dataset.code across rows cleanly in one pass
  3. 03Stops live-loop bugsPrevents infinite loops when adding elements during iteration
Copied JavaScript ArrayStatic snapshot [D1, D2, D3] with full array methods

Learn [...list] once: it fixes missing array methods on NodeList and snapshots live HTMLCollections.

Interactive Practice Lab

Edit and run this snippet directly in your browser (zero setup)

JavaScript
const scores = [78, 92, 64, 95, 88];const passed = scores.filter((n) => n >= 70);const avg = passed.reduce((a, b) => a + b, 0) / passed.length;console.log('Passed count:', passed.length);console.log('Average score:', avg.toFixed(1));

Live Big-O Complexity & Binary Search Race Lab

Compare complexity curves at scale and watch Linear vs Binary Search race live.

Spread it and everything works:
[...document.querySelectorAll('.dock')].map(li => li.dataset.code)
answers D1, D2, D3. That is the idiom to learn once. It also copies,
which turns a live collection into a safe snapshot, so the never-ending loop
above is fixed by the same three characters.

Four methods that replace most DOM code people write

  • dataset reads a data- attribute as a property, so
    li.dataset.code answers D1 with no
    getAttribute and no string key
  • closest('ul') walks up from an element to the nearest matching
    ancestor, and .id on the result answers docks, which
    is how a click on a child finds the row it belongs to
  • matches('.out') asks whether an element satisfies a selector
    and answers true or false, which is the test inside every delegated handler
  • textContent gives the text of an element and its descendants,
    so the first item answers "Rasht 8", one string from two nodes

Those four together are event delegation: put one listener on the list,
and in the handler use event.target.closest('.dock') to find which
row was clicked and matches to decide whether to act. One listener
survives rows being added and removed; a listener per row does not, which is the
same live-against-static problem in another costume.

The page, as the selectors see it

What is inside what, and where each method starts from

Every selector on this page is a question about this tree, and the only thing that differs between them is whether the answer keeps looking.

document

  • ul#docksWhere one delegated listener belongs
    • li.dock[data-code=D1]textContent is Rasht 8, from this node and the span inside it
      • span.bikesclosest('ul') from here answers docks
    • li.dock[data-code=D2]
    • li.dock.out[data-code=D3]matches('.out') is true, and nothing else here matches it
    • li.dock[data-code=D4]Appended after both selectors ran. Only the live one counts it
  • button#refreshOutside the list, so a delegated handler on ul never sees it

The figure draws the tree after the append. A static NodeList taken before it is a picture of the same tree with the last row missing, and nothing about that list will ever tell you so.

What to run in 2026

The browser's own element inspector is the tool, free in every browser, and
the part worth using is the Properties panel rather than the markup: it shows
the live object, so dataset, classList and the
attached listeners are all readable without a single
console.log. It replaced logging the element and expanding the
output, which prints a snapshot that has already changed.

Built-in browser workflow

Two native tools that replace brittle DOM habits

Inspect live object state directly in DevTools and toggle classes safely through classList instead of concatenating strings.

Clean browser DOM inspection and updates
  • Inspector Properties panelShows live dataset, classList, and listeners without stale console.log snapshots
  • element.classList APIUses add, remove, and toggle instead of substring-breaking className strings

Built into every modern browser

Neither requires a library, and both eliminate entire categories of stale-log and class-string bugs.

element.classList is the API to reach for rather than writing
className, free with the language and universal since about 2012.
add, remove and toggle replaced string
concatenation on the class attribute, which is how a class gets added twice and
how removing one class removes a second one that happened to share a
substring.

Where this stalls people

The stall is holding on to elements. A reference selected at load, kept in a
variable and used later works perfectly until anything re-renders that part of
the page, at which point the variable points at a detached element: every method
still works, nothing raises, and the changes go to a node that is not in the
document. It looks like the code did not run.

Stale element references

How caching a row element silently drops updates

Holding onto a DOM node across a re-render causes updates to succeed in memory on an element no longer attached to the page.

Treat the live document as the source of truth rather than a variable captured earlier.

The habit that avoids it entirely is to select inside the handler rather than
outside it, and to hold onto a container rather than a row. That is the same
advice as event delegation and it comes from the same fact: the document is the
state, and anything you cached is a copy that can go stale. Which values arrive
in those handlers, and when, is
callbacks,
promises and await
, the language rules underneath are
types, functions
and the parts that surprise people
, and the structure being walked is
hierarchies, and
searching one without reading it all
, all inside
the only language a browser
runs
.

Alongside this

Above this