Selecting Elements in JavaScript
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.
querySelector(All) first
document.querySelector("#app .item") — full CSS selector power for first/all matches.
NodeLists aren't arrays
[...document.querySelectorAll("li")] spreads to a true array — map/filter then work.
Null-check misses
No match means null — guard before property access or face the classic null-property TypeError.
Scope and cache
root.querySelector searches subtrees; cache lookups outside hot paths instead of re-querying per frame.
let first = document.querySelector("#list li");let items = [...document.querySelectorAll("#list li")];console.log(first !== null, items.length);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.