HTML DOM querySelector () method
Examples
The first child element text content modification id = "demo" of the <div> element:
x.querySelector ( "# demo") innerHTML = "Hello World!".;
try it"
Definition and Usage
querySelector () method returns the matching element specified CSS selector first child element.
Note: querySelector () method simply returns the first element that matches the specified selector. If you want to return all matching elements, use querySelectorAll () method instead.
For more CSS selectors, you can 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 Element 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
Modify <div> element in the first <p> element's content:
x.querySelector ( "p") innerHTML = "Hello World!".;
try it"
Examples
Modify <div> element in the first class = "example" sub-element content:
x.querySelector ( "example.") innerHTML = "Hello World!".;
try it"
Examples
Modify <div> element in the first class = "example" of the <p> element:
x.querySelector ( "p.example") innerHTML = "Hello World!".;
try it"
Examples
Add red border as a <div> element has a first target attribute <a> elements:
. X.querySelector ( "a [target]") style.border = "10px solid red";
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 for the following code <div> element to add a background color:
<H2> A h2 element </ h2>
<H3> A h3 element </ h3>
</ Div>
var x = document.getElementById ( "myDIV");
x.querySelector ( "h2, h3") style.backgroundColor = "red".;
try it"
However, if the <div> element <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>
</ Div>
var x = document.getElementById ( "myDIV");
x.querySelector ( "h2, h3") style.backgroundColor = "red".;
try it"
Related Pages
JavaScript Reference Manual: document.querySelector ()