JavaScript Interview Question #52
What is the difference between document.getElementById() and querySelector()?
DOM, Events & Event Loop Fundamentals Mid-Level Intermediate
Quick Interview Answer
getElementById searches for an element by its id and returns that element or null. querySelector accepts any valid CSS selector and returns the first matching element or null.
Detailed Explanation
getElementById searches for an element by its id and returns that element or null. querySelector accepts any valid CSS selector and returns the first matching element or null.
getElementById is direct and clear when an id is available. querySelector is more flexible because it can select by class, attribute, element type, relationships, and other CSS selector patterns.
Code Example
const byId = document.getElementById("saveButton");
const firstButton = document.querySelector(".btn-primary");
console.log(byId, firstButton);