querySelector vs getElementById
document.getElementById('id') finds one element by its id. querySelector('css selector') finds the first element matching any CSS selector and can be called on any element, not just document. Both return null when nothing matches.
document.getElementById('save'); // id only, no '#'
document.querySelector('#save'); // same element, via a selector
document.querySelector('form .btn[type="submit"]'); // anything CSS can express
1. Side by side
getElementById |
querySelector |
|
|---|---|---|
| Input | An id string | A CSS selector |
| Called on | document (and document fragments) |
document or any element |
| Returns | One element or null |
First match or null |
| Many results | n/a | querySelectorAll |
| Invalid input | Returns null |
Throws SyntaxError |
| Speed | Fastest | Slightly slower; rarely matters |
2. Scoped lookups
querySelector searches inside the element you call it on:
const card = document.querySelector('.card');
const title = card.querySelector('h2'); // only inside this card
const direct = card.querySelector(':scope > .badge'); // direct children only
getElementById doesn’t exist on elements, because an id is meant to be unique in the whole document.
3. Live vs static collections
This is the follow-up interviewers ask most.
const live = document.getElementsByClassName('item'); // HTMLCollection, live
const frozen = document.querySelectorAll('.item'); // NodeList, static
document.body.append(Object.assign(document.createElement('div'), { className: 'item' }));
live.length; // increased by 1
frozen.length; // unchanged
getElementsByClassNameandgetElementsByTagNamereturn a liveHTMLCollectionthat updates as the DOM changes. Removing items while looping over it skips elements.querySelectorAllreturns a staticNodeList: a snapshot. It hasforEach; anHTMLCollectiondoesn’t.
Convert either with Array.from(...) or [...collection] to use map and filter.
4. Ids that break selectors
getElementById takes the id literally. A selector has to follow CSS syntax:
// <div id="1st.item">
document.getElementById('1st.item'); // works
document.querySelector('#1st.item'); // SyntaxError
document.querySelector('#' + CSS.escape('1st.item')); // works
document.querySelector('[id="1st.item"]'); // works
Ids generated by frameworks (for example ones containing colons) need the same treatment.
5. Performance
Browsers keep an id lookup table, so getElementById is the fastest call. querySelector('#id') is nearly as fast, and complex selectors cost more. In practice the difference only shows up inside hot loops over large documents. Cache the result instead of looking it up repeatedly:
const list = document.getElementById('list');
for (const item of data) list.append(render(item));
6. Related methods
element.closest(selector): nearest ancestor (or itself) that matches. Essential for event delegation.element.matches(selector): does this element match?
7. In React
Don’t query the DOM for elements React renders. Use a ref, so you get the right node even when the component is used more than once.
Choosing a method
| Need | Use |
|---|---|
| One element with a known, simple id | getElementById |
| First match for any selector | querySelector |
| All matches as a snapshot | querySelectorAll |
| A collection that tracks DOM changes | getElementsByClassName / getElementsByTagName |
| Search within a component’s root | root.querySelector(...) |
| Walk up from an event target | event.target.closest(...) |
Follow-up questions to expect
- “Implement
getElementsByClassNamewithout the built-in.” A depth-first walk checkingclassList. Try it: getElementsByClassName. - “Implement
querySelectorAllfor simple selectors.” See build your own querySelectorAll. - “What if two elements share an id?” The HTML is invalid.
getElementByIdreturns the first in document order;querySelectorAll('#id')returns both.
