HTML DOM querySelector() method
Example
Get the element with id="demo" in the document:
document.querySelector("#demo");
Try it »
Definition and Usage
The querySelector() method returns the first element in the document that matches a specified CSS selector.
Note: The querySelector() method only returns the first element that matches the specified selector. If you need to return all elements, use the querySelectorAll() method instead.
For more CSS selectors, please visit our CSS Selector Tutorial and our CSS Selector Reference Manual.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| querySelector() | 4.0 | 8.0 | 3.5 | 3.1 | 10.0 |
Syntax
document.querySelector(
CSS selectors
)
Parameter value
| Parameters | Type | Description |
|---|---|---|
| CSS selector | String | Required. One or more CSS selectors that match elements. You can use their id, class, type, attribute, attribute value, etc. to select elements. |
对于多个选择器,使用逗号隔开,返回一个匹配的元素。
Hint: More CSS selectors, See also our [CSS Selector Reference Manual](/cssref/css-selectors.html).
Technical Details
| DOM version: | Selectors Level 1 Document Object |
|---|---|
| Return value: | The first element that matches the specified CSS selector. If not found, returns null. If an invalid selector is specified, a SYNTAX_ERR exception is thrown. |
More examples
Example
Get the first
element:
document.querySelector("p");
Try it »
Example
Get the first element with class="example" in the document:
document.querySelector(".example");
Try it »
Example
Get the first element with class="example" in the document
element:
document.querySelector("p.example");
Try it »
Example
Get the first element in the document that has the "target" attribute element:
document.querySelector("a[target]");
Try it »
Example
The following example demonstrates the use of multiple selectors.
Suppose you select two selectors:
and
.
The following code will set the background color for the first
element in the document:
A h2 element
A h3 element
document.querySelector("h2, h3").style.backgroundColor = "red";
Try it »
However, if the document contains a
element located before a
element,
the element will be set with the specified background color.
A h3 element
A h2 element
document.querySelector("h2, h3").style.backgroundColor = "red";
Try it »
Related pages
JavaScript Reference Manual: element.querySelector()
Document Object