ComparisonComparisons

querySelector() vs getElementById()

querySelector() accepts any CSS selector and returns the first matching element, while getElementById() only searches by the id attribute, but is simpler.

On this page

Side-by-side comparison

#

Example

#
JavaScript
const byId = document.getElementById('task-2')
const bySelector = document.querySelector('#task-2')
const byClass = document.querySelector('.task:not(.done)')

console.log(byId === bySelector)
console.log(byClass.textContent)
console.log(document.getElementById('task-3'))
Console
true
CSS
null

Definition and usage

#

Both methods return the first matching element, or null when they find nothing, and both read the existing document without creating new elements. What sets them apart is what they search for. querySelector() accepts any CSS selector, such as ".card", "nav a", or "input[type=email]". getElementById() accepts just the value of the id attribute, without the # character, because it isn’t a CSS selector.

querySelector() can be called not only on document, but also on any element, and then it only searches inside it. getElementById() only works on document. Searching by id, meanwhile, is the fastest operation in the DOM, because the browser can reach the element directly, without parsing a selector.

Have a simple identifier known up front and searching the whole document? getElementById() is simpler and faster. Need a class, an attribute, a nested selector, or to search inside a specific element? Reach for querySelector().

Syntax

#
Syntax
document.querySelector(selectors)
element.querySelector(selectors)

document.getElementById(id)

More examples

#
getElementById() only works on document
JavaScript
const card = document.querySelector('#html-course')
const price = card.querySelector('.price')

console.log(price.textContent)
console.log(typeof card.getElementById)
Console
$49
undefined

An element has no getElementById() method, only document does. When searching inside a specific element, always use querySelector() or querySelectorAll().

Both methods are case-sensitive
JavaScript
console.log(document.getElementById('Submit-Btn')?.textContent)
console.log(document.getElementById('submit-btn'))
console.log(document.querySelector('#Submit-Btn')?.textContent)
Console
Send
null
Send

Good practices

#
  • Have a simple, unique id? getElementById() is the fastest and most readable solution.
  • Need to search only inside a specific element? Call querySelector() on that element, not on document. getElementById() can’t do that.
  • Check the result before using it, or use ?.. Both methods return null when they find nothing.

Related entries

#

Spotted a mistake or missing an example? Write to us.