Document

document.querySelector

Returns the first Element within the document that matches the specified CSS selector, or null if no matches are found

Syntax

JavaScript
document.querySelector(selectors)

Parameters

ParameterTypeDescription
selectorsstringA string containing one or more CSS selectors to match

Return Value

The first Element matching the selector, or null

Examples

Basic Usage
const heading = document.querySelector('h1')
console.log(heading?.textContent)
Practical Example
const activeItem = document.querySelector('.nav-item.active')
if (activeItem) {
  console.log('Active:', activeItem.textContent)
}
Advanced Usage
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

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.