Latest web development tutorials

HTML DOM querySelector () method

Document Object Reference Document Object

Examples

Get the first element of the document id = "demo" of:

document.querySelector ( "# demo");

try it"

Definition and Usage

querySelector () method returns an element in the document that match the specified CSS selector.

Note: querySelector () method simply returns the first element that matches the specified selector. If you need to return all of the elements, use querySelectorAll () method instead.

More CSS selectors, please visit our CSS selectors tutorial and our CSS selectors reference manual .


Browser Support

Figures in the table represent the first browser to support the method version number.

method
querySelector () 4.0 8.0 3.5 3.1 10.0


grammar

document.querySelector (CSS selectors)

Parameter Value

parameter Types of description
CSS selectors String have to. Specify one or more matching elements in CSS selectors. You can use their id, classes, types, attributes, attribute values, etc. to select elements.

For multiple selectors, separated by commas, to return a matching element.

Tip: For more CSS selectors, please see our CSS selectors reference manual .

technical details

DOM version: Selectors Level 1 Document Object
return value: The first matching element specified CSS selector. If not found, returns null. If you specify an invalid selector SYNTAX_ERR exception is thrown.


More examples

Examples

Being the first document in a <p> element:

document.querySelector ( "p");

try it"

Examples

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

document.querySelector ( "example.");

try it"

Examples

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

document.querySelector ( "p.example");

try it"

Examples

Get the document has "target" attribute first <a> elements:

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

try it"

Examples

The following example demonstrates the use of a plurality of selectors.

Suppose you choose the two selectors: <h2> and <h3> element.

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

<H2> A h2 element </ h2>
<H3> A h3 element </ h3>

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

try it"

However, if your document <h3> element is <h2> element before, <h3> element will be set to specify the background color.

<H3> A h3 element </ h3>
<H2> A h2 element </ h2>

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

try it"


Related Pages

JavaScript Reference Manual: Element .querySelector ()


Document Object Reference Document Object