Learn JavaScript
❯ browser_dom.dom_select

Selecting Elements in JavaScript

$concept

DOM selection starts with CSS selectors: querySelector returns the first match, querySelectorAll returns all matches as a static NodeList (array-like — spread it for map/filter). Legacy getElementById/getElementsByClassName still work but return live collections with surprising update semantics.

Select narrowly (IDs and data-attributes over bare tags), cache repeated lookups outside loops and handlers, and null-check results — querySelector returns null on misses, and the #1 DOM bug is operating on it. Scoped root.querySelector confines searches to subtrees.

$how it works
1

querySelector(All) first

document.querySelector("#app .item") — full CSS selector power for first/all matches.

2

NodeLists aren't arrays

[...document.querySelectorAll("li")] spreads to a true array — map/filter then work.

3

Null-check misses

No match means null — guard before property access or face the classic null-property TypeError.

4

Scope and cache

root.querySelector searches subtrees; cache lookups outside hot paths instead of re-querying per frame.

$example
let first = document.querySelector("#list li");
let items = [...document.querySelectorAll("#list li")];
console.log(first !== null, items.length);
Output
(true and the item count, e.g. true 3)
1querySelector grabs the first matching list item or null.
2querySelectorAll plus spread materializes every match as a real array.
3Existence plus count print — selection verified before any manipulation.
$use cases
Grabbing app roots and controls by ID and data-attributes
Bulk operations via spread-then-map over NodeLists
Null-guarding every selection before use
Scoping queries to components with root selectors

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.