JavaScriptEasy
Explain the difference between document.querySelector() and document.getElementById()
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
document.querySelector() and document.getElementById() are both methods used to select elements from the DOM, but they have key differences. document.querySelector() can select any element using a CSS selector and returns the first match, while document.getElementById() selects an element by its ID and returns the element with that specific ID.
js
// Using document.querySelector()
const element = document.querySelector(".my-class");
// Using document.getElementById()
const elementById = document.getElementById("my-id");
