English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
document.querySelector(selectors)
document.querySelector('h1');Test and See‹/›
The numbers in the table specify the first browser version that fully supports the querySelector() method:
Method | |||||
querySelector() | 1 | 3.5 | 10 | 3.2 | 8 |
Parameter | Description |
---|---|
selectors | A string containing one or more selectors to match. This string must be a validCSS SelectorString |
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 |
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‹/›
CSS Tutorial:CSS Selector
CSS Reference:CSS #idSelector
CSS Reference:CSS .classSelector
DOM Document querySelectorAll()Methods
DOM Document getElementsByClassName()Methods
DOM Document getElementsByTagName()Methods