Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

document.querySelector()

Reference for querySelector(): find the first element that matches a CSS selector in a document or element, with null handling, scoping and edge cases.

querySelector() returns the first element in document order that matches a CSS selector, or null if nothing matches. It exists on document, on every element, and on document fragments, so you can search the whole page or only inside one component.

Because it accepts any selector you could write in a stylesheet, one method covers lookups by id, class, attribute, position and relationship.

JavaScript
const first = document.querySelector(".card");
const link = form.querySelector("a[href^='https']");

Try it

Find the first match
Scoped search and null safety

Syntax

JavaScript
document.querySelector(selectors)
element.querySelector(selectors)
Name Description
selectors A string containing one selector or a comma-separated selector list. Special characters in ids and class names must be escaped (see CSS.escape()).

Return value: the first matching Element in document order (depth-first, as the elements appear in the markup), or null.

Exceptions: a SyntaxError DOMException if the string is not a valid selector.

Usage notes

  • Always consider null. Reading a property of the result without a check throws a TypeError when the element is missing. Use if, or optional chaining as in document.querySelector(".promo")?.remove().
  • First in document order, not first in the selector list. For "h3, h2" you get whichever matching heading comes first on the page.
  • Scoped searches only look at descendants. el.querySelector("p") never returns el itself. The selector is still evaluated against the whole document, though, so a selector like div p can match when div is an ancestor outside el. Use :scope > p to anchor the search to el.
  • The result is a live element, not a copy. Changing it changes the page. The lookup itself is a snapshot; later DOM changes do not update the variable you stored.
  • Shadow DOM. The method does not look inside shadow trees. Call it on the shadow root.
  • Pseudo-elements and state. Pseudo-elements such as ::before never match. Dynamic pseudo-classes such as :hover can be used but match only at that moment.
  • getElementById() is faster in theory, but the difference rarely matters; choose whichever reads better.
  • Many results? Use querySelectorAll().

Browser support

Supported by every current browser, and has been for many years. Newer selectors such as :has() depend on the browser's CSS support, so check a compatibility table.