Favorites

DOM Document.querySelector() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Document.querySelector()
DOM Document MethodThis method is supported by all modern browsers.
Updated 28th November 2026

The document.querySelector() method returns the first element in the page that matches a CSS selector, or null.

Description

The querySelector() method of Document returns the first element in the document that matches the CSS selectors, searching in document order, or null if there's none. It accepts any selector, so it can find elements by ID, class, attribute, position or state. Always handle the null case before using the result.

To search within one part of the page, call querySelector() on an element instead.

Selectors that start with a digit or contain special characters, such as an ID like "1st", need escaping; CSS.escape() handles that for you. Searching for an ID is slightly faster with getElementById(), though the difference rarely matters.

Syntax

document.querySelector(selectors)

Parameters

  • selectorsA string of one or more CSS selectors.

Return Value

The first matching element in the document, or null if there is no match.

Exceptions

  • SyntaxErrorThrown if the selectors are not valid CSS.

Example

<ul>
  <li class="price">$10</li>
  <li class="price" data-sale>$8</li>
</ul>
console.log(document.querySelector('.price').textContent);
console.log(document.querySelector('[data-sale]').textContent);
console.log(document.querySelector('li:nth-child(2)').textContent);
const missing = document.querySelector('.nope');
console.log(missing?.textContent ?? 'not found');

Browser Support

The following information will show you the current browser support for the Document.querySelector() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee