document.querySelector(selectors) returns the firstElement in the document that matches a CSS selector (or group of selectors). If nothing matches, it returns null. Matching walks the tree in document order (depth-first).
Pass the required arguments shown below. Check return values and browser support before you rely on the result.
Syntax
Call document.querySelector. Start with this line.
JavaScript
document.querySelector(selectors)
Call
What it does
document.querySelector(selectors)
Primary signature.
document.querySelector(...)
Call with the arguments your case needs.
Built into the browser. Call querySelector(...) on document — no import required.
Library declarations
JavaScript
document.querySelector(selectors)
Parameters
Parameter
Description
selectors
Required. Valid CSS selector string
Return Value
Return Value
Description
*
First matching Element, or null
JavaScript Examples
Example 1 — First Element with a Class
MDN-style: return the first element that has class myclass.
JavaScript
const el = document.querySelector(".myclass");
console.log(el ? el.textContent : null);
// first .myclass text, or null
It returns the first Element in the document that matches a CSS selector (or group of selectors). If nothing matches, it returns null.
No. MDN marks Document.querySelector() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
The method returns null. Always check for null before reading properties like textContent or className.
A SyntaxError DOMException is thrown if the selectors string is not valid CSS.
querySelector() returns the first matching Element (or null). querySelectorAll() returns a static NodeList of all matches. Use querySelectorAll when you need every match.
When you have a unique, simple id and want the classic fast path. Use querySelector when you need classes, attributes, combinators, or :not() — and escape special characters in ids with CSS.escape().