document.querySelector
Returns the first Element within the document that matches the specified CSS selector, or null if no matches are found
Syntax
document.querySelector(selectors)Parameters
| Parameter | Type | Description |
|---|---|---|
| selectors | string | A string containing one or more CSS selectors to match |
Return Value
The first Element matching the selector, or null
Examples
const heading = document.querySelector('h1')
console.log(heading?.textContent)const activeItem = document.querySelector('.nav-item.active')
if (activeItem) {
console.log('Active:', activeItem.textContent)
}const input = document.querySelector<HTMLInputElement>('input[name="email"]')
if (input) {
console.log(input.value)
}Understanding document.querySelector
The document.querySelector method in JavaScript returns the first Element within the document that matches the specified CSS selector, or null if no matches are found. It belongs to the Document object and is one of the most widely used methods for working with document values in modern JavaScript and TypeScript applications.
The method signature is document.querySelector(selectors). It accepts 1 parameter: selectors. When called, it returns the first element matching the selector, or null. Understanding when and how to use querySelector() helps you write more expressive, readable code.
Common use cases for document.querySelector include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-queryselectorall, dom-getelementbyid, dom-getelementsbyclassname, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for document.querySelector is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
document.querySelectorAllReturns a static NodeList representing a list of the document's elements that match the specified group of CSS selectors
document.getElementByIdReturns an Element object representing the element whose id property matches the specified string
document.getElementsByClassNameReturns a live HTMLCollection of all child elements which have all of the given class names
More Document Methods
Other methods in the Document object
Related Tools
More Document Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.