English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM querySelector() method

HTML DOM Document Object

querySelector()Returns the first element in the document that matches the specified selector or selector group.

If no matches are found, it returns null.

The querySelector() method returns only the first element that matches the specified selector. To return all matches, please usequerySelectorAll()Method.

Syntax:

document.querySelector(selectors)
document.querySelector('h1');
Test and See‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the querySelector() method:

Method
querySelector()13.5103.28

Parameter value

ParameterDescription
selectorsA string containing one or more selectors to match. This string must be a validCSS SelectorString

Technical details

Return value:Represents theCSS SelectorThe Element object of the first element matched by the set, if no match is found, it returns null.
Exception cases:SyntaxError-The syntax of the specified selector string is invalid
DOM Version:DOM Level1

More Examples

Get the first element with id="para":

document.querySelector('#para');
Test and See‹/›

Get the first element using class="demo":

document.querySelector(".demo");
Test and See‹/›

Get the first <p> element that is a child of the <div> element in the document:

document.querySelector("div > p");
Test and See‹/›

Related References

CSS Tutorial:CSS Selector

CSS Reference:CSS #idSelector

CSS Reference:CSS .classSelector

DOM Document querySelectorAll()Methods

DOM Document getElementsByClassName()Methods

DOM Document getElementsByTagName()Methods

HTML DOM Document Object