Query Selector vs Select Element – What they return
A brief look at some commonly used methods on the document object:
- getElementById
- getElementsByClassName
- querySelector
- querySelectorAll
document.getElementById("id-name")
document.getElementById("id-name")
- returns a single element
- IDs should be unique per page
There are a few valid ID naming styles — just be consistent:
- camelCase → thisWorks
- dashes → this-works
- snake_case → this_works
document.getElementsByClassName("class-name")
- returns an HTMLCollection
- not a true array
You can convert it to an array:
Array.from(collection)Then you can use:
forEach()
map()Memory trick:
C → C → C
ClassName → Collection → Converts
document.querySelector(".class-name")
- returns the first matching element
You must be explicit because it uses CSS selector syntax:
// Class
querySelector(".class-name")
// ID
querySelector("#id-name")
// Element
querySelector("img")
// Data attribute
querySelector("[data-btn]")Some developers use data attributes for JavaScript to avoid mixing styling and behavior:
<button class="bg-blue-500" data-btn></button>document.querySelector("[data-btn]")document.querySelectorAll("p")
- returns a NodeList
- similar to an array
Works with:
forEach()Does NOT work with:
map()Convert it if needed:
Array.from(nodeList)or
[...nodeList]Mental Model
HTML builds a tree (the DOM).
Think of it like a giant treehouse.
- JavaScript has a ‘map’ or access ’to the whole structure (document)
- But you need to select elements to interact with them
Does JavaScript “know” elements exist without selecting them?
Yes.
JavaScript can:
- run logic
- define functions
- work with data
But selecting an element gives you a handle to it.
So you can:
- add event listeners
- update content
- toggle classes
- manipulate styles
Final takeaway
Selection is the bridge between JavaScript logic and what the user actually sees.