JavaScriptDOM and events

document.querySelector()

Returns the first element that matches a CSS selector, or null when nothing matches.

Returns
The first matching element, or null.
On this page

Example

#
JavaScript
const first = document.querySelector('.task')
const todo = document.querySelector('.task:not(.done)')
const last = document.querySelector('.tasks li:last-child')

console.log(first)
console.log(todo.textContent)
console.log(last.textContent)
console.log(document.querySelector('.missing'))
Console
<li class="task done">
CSS
JavaScript
null

Definition and usage

#

The querySelector() method searches the document and returns the first element that matches the given CSS selector. You can use any selector you know from stylesheets: "#menu", ".card", "nav a", "input[type=email]", or "li:last-child".

If no element matches, the method returns null. Reading a property from null throws an error, so for elements that might not be on the page, check the result or use the ?. operator.

You can call the method not only on document, but on any element too. Then it only searches inside that element, which is handy for repeating page fragments, such as course cards. To get every matching element, use querySelectorAll().

Syntax

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

Parameters

#
  • selectors

    string

    A CSS selector, e.g. "#menu" or ".card h3". Separate multiple selectors with commas.

More examples

#
Searching inside an element
JavaScript
const cssCard = document.querySelector('#css-course')
const price = cssCard.querySelector('.price')

console.log(cssCard)
console.log(price.textContent)
Console
<article id="css-course" class="card">
$59
A safe read with ?.
JavaScript
const banner = document.querySelector('.promo-banner')

console.log(banner?.textContent ?? 'No banner on the page')
console.log(document.querySelector('#save').textContent)
Console
No banner on the page
Save

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Check the result before using it, or use ?.. A typo in the selector ends in a “Cannot read properties of null” error.
  • Search inside a specific element (card.querySelector()) when the page has many similar fragments.
  • An id that starts with a digit needs special escaping in a selector. In that case, it’s simpler to use getElementById().

Related entries

#

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