querySelector vs getElementById
The 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:
1const 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:
1// By ID2const header = document.querySelector('#main-header');34// By class5const button = document.querySelector('.submit-btn');67// By tag8const firstParagraph = document.querySelector('p');910// By attribute11const emailInput = document.querySelector(12 'input[type="email"]'13);1415// Complex selector16const item = document.querySelector(17 '.list > li:first-child'18);
- 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:
1const allButtons = document.querySelectorAll('.btn');23// Returns a NodeList — you can loop over it4allButtons.forEach((button) => {5 button.addEventListener('click', handleClick);6});
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.