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.
const first = document.querySelector(".card"); const link = form.querySelector("a[href^='https']");
Try it
Syntax
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 aTypeErrorwhen the element is missing. Useif, or optional chaining as indocument.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 returnselitself. The selector is still evaluated against the whole document, though, so a selector likediv pcan match whendivis an ancestor outsideel. Use:scope > pto anchor the search toel. - 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
::beforenever match. Dynamic pseudo-classes such as:hovercan 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.