HTML DOM querySelector () method
Examples
Get the first element of the document id = "demo" of:
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
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
Get the document class = "example" the first element:
try it"
Examples
Get the document class = "example" the first <p> element:
try it"
Examples
Get the document has "target" attribute first <a> elements:
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:
<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.
<H2> A h2 element </ h2>
document.querySelector ( "h2, h3") style.backgroundColor = "red".;
try it"
Related Pages
JavaScript Reference Manual: Element .querySelector ()