HTML DOM querySelector()Method

Document 对象参考手册Document Object

Example

Get the element with id="demo" in the document:

document.querySelector("#demo");

Try it Yourself »

Definition and Usage

The querySelector() method returns the first element in the document that matches the 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, visit ourCSS Selector Tutorialand ourCSS Selector Reference Manual。


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
querySelector() 4.0 8.0 3.5 3.1 10.0


Syntax

document.querySelector(CSS selectors)

Parameter Values

Parameter Type Description
CSS selector String Required. Specifies a CSS selector for one or more elements to match. You can select elements by their id, class, type, attribute, attribute value, etc.

For multiple selectors, separate them with commas, and returns a matching element.

Tip:For more CSS selectors, see ourCSS Selector Reference Manual。

Technical Details

DOM Version: Selectors Level 1 Document Object
Return Value: The first element that matches the specified CSS selector. If no matches are found, null is returned. If an invalid selector is specified, a SYNTAX_ERR exception is thrown.


More Examples

Example

Get the first <p> element in the document:

document.querySelector("p");

Try it Yourself »

Example

Get the first element with class="example" in the document:

document.querySelector(".example");

Try it Yourself »

Example

Get the first <p> element with class="example" in the document:

document.querySelector("p.example");

Try it Yourself »

Example

Get the first <a> element in the document that has a "target" attribute:

document.querySelector("a[target]");

Try it Yourself »

Example

The following example demonstrates the use of multiple selectors.

Suppose you select two selectors: the <h2> and <h3> elements.

The following code will add a background color to the first <h2> element in the document:

<h2>A h2 element</h2>
<h3>A h3 element</h3>

document.querySelector("h2, h3").style.backgroundColor = "red";

Try it Yourself »

However, if the <h3> element is located before the <h2> element in the document, the <h3> element will be set to the specified background color.

<h3>A h3 element</h3>
<h2>A h2 element</h2>

document.querySelector("h2, h3").style.backgroundColor = "red";

Try it Yourself »


Related Pages

JavaScript Reference Manual:element.querySelector()


Document 对象参考手册Document Object

Other Extensions