querySelector vs getElementById
JavaScriptThe short answer
getElementById selects an element by its ID and returns a single element. querySelector uses CSS selectors and can match any element (by ID, class, tag, attribute, or combination). getElementById is slightly faster for ID lookups, but querySelector is more flexible.
getElementById
Selects a single element by its id attribute:
const header = document.getElementById('main-header');- Takes an ID string (without the
#symbol) - Returns one element or
nullif not found - Only works with IDs
querySelector
Selects the first element that matches a CSS selector:
// By IDconst header = document.querySelector('#main-header');// By classconst button = document.querySelector('.submit-btn');// By tagconst firstParagraph = document.querySelector('p');// By attributeconst emailInput = document.querySelector( 'input[type="email"]');// Complex selectorconst item = document.querySelector( '.list > li:first-child');- Takes any valid CSS selector
- Returns the first matching element or
null - Much more flexible than
getElementById
querySelectorAll
If you need all matching elements, use querySelectorAll:
const allButtons = document.querySelectorAll('.btn');// Returns a NodeList — you can loop over itallButtons.forEach((button) => { button.addEventListener('click', handleClick);});Note: querySelectorAll returns a static NodeList, not a live collection. If you add or remove elements after calling it, the NodeList does not update.
Which one to use
- For ID selection: Both work.
getElementByIdis marginally faster, but the difference is negligible. - For anything other than ID: Use
querySelectororquerySelectorAll—getElementByIdonly works with IDs. - In modern code:
querySelectoris the standard choice because it handles all cases with a familiar CSS selector syntax.
Interview Tip
Keep the answer short. The main point is that querySelector is more flexible because it accepts any CSS selector, while getElementById only works with IDs. Mention querySelectorAll for selecting multiple elements. In React projects, you rarely use these directly because React manages the DOM for you.
Why interviewers ask this
This tests basic DOM API knowledge. Interviewers want to see if you know how to select elements and which method to use for different situations. It is a fundamental skill for any frontend developer.