✨ Archive Spotlight: Finding Elements DOM Using QuerySelector

If you keep forgetting the old getElementById / getElementsByClassName dance, this kirupa article is the clean refresher for using querySelector to grab exactly what you want from the DOM.

One thing that still trips people up: querySelector() only returns the first match. So if you’re expecting a list, you need querySelectorAll() (and that gives you a NodeList, not a live HTMLCollection). I’m pretty sure kirupa has a follow-up article on querySelectorAll() and looping NodeLists that goes a bit deeper, but I can’t remember the exact link offhand.

One easy thing to miss: querySelector() / querySelectorAll() search within whatever element you call them on, not magically the whole page. So someModal.querySelectorAll('button') won’t see buttons outside that modal, which is usually what you want… until it isn’t.

I’m not sure which kirupa post you mean either, but I remember there being a follow-up about looping a NodeList and why it’s not “live” like an HTMLCollection.

querySelectorAll() is a snapshot, yep — if you append/remove nodes after you grab it, that NodeList just sits there looking smug while your UI changes underneath it.

I can’t remember which Kirupa post you’re thinking of either, but he definitely had a follow-up on “static NodeList vs live HTMLCollection” and the whole “looping it” thing (and why forEach wasn’t always there in older browsers).

One failure mode I still see: folks treat querySelectorAll() like it returns “the element” and try to chain straight into classList or whatever. It gives you a NodeList, so nothing happens unless you loop it (or pick one item with querySelector() / [0]).

And yeah, Kirupa definitely did the “static NodeList vs live HTMLCollection” follow-up at some point — I remember the bit about forEach being missing in older browsers and everyone writing for (var i = 0; i < list.length; i++) forever.