HTML DOM querySelector()Method
Examples
Modify the text content of the first child element of the <div> element with class="demo":
Try it Yourself »
Definition and Usage
The querySelector() method returns the first child element that matches the specified CSS selector of an element.
Note:The querySelector() method only returns the first element that matches the specified selector. If you want to return all matching elements, use the querySelectorAll() method instead.
For more CSS selectors, you can visit ourCSS Selectors Tutorialand ourCSS Selectors Reference。
Browser Support
The numbers in the table specify the first browser version that supports the method.
| Method | |||||
|---|---|---|---|---|---|
| querySelector() | 4.0 | 8.0 | 3.5 | 3.1 | 10.0 |
Syntax
Parameter Values
| Parameter | Type | Description |
|---|---|---|
| CSS Selector | String | Required. Specifies one or more CSS selectors to match the element. You can select elements by their id, class, type, attribute, attribute value, etc. For multiple selectors, separate them with commas, and a matching element is returned. Tip:For more CSS selectors, please refer to ourCSS Selectors Reference。 |
Technical Details
| DOM Version: | Selectors Level 1 Element Object |
|---|---|
| Return Value: | The first element that matches the specified CSS selector. If no match is found, returns null. If an invalid selector is specified, a SYNTAX_ERR exception is thrown. |
More Examples
Examples
Modify the content of the first <p> element inside a <div> element:
x.querySelector("p").innerHTML = "Hello World!";
Try it Yourself »
Examples
Modify the content of the first child element with class="example" inside a <div> element:
x.querySelector(".example").innerHTML = "Hello World!";
Try it Yourself »
Examples
Modify the first <p> element with class="example" inside a <div> element:
x.querySelector("p.example").innerHTML = "Hello World!";
Try it Yourself »
Examples
Add a red border to the first <a> element inside a <div> element that has a target attribute:
x.querySelector("a[target]").style.border = "10px solid red";
Try it Yourself »
Examples
The following examples demonstrate the usage of multiple selectors.
Suppose you have selected two selectors: the <h2> and <h3> elements.
The following code will add a background color to the first <h2> element inside a <div> element:
<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 Yourself »
However, if the <h3> element is placed before the <h2> element inside the <div> element, the specified background color will be set to the <h3> element.
<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 Yourself »
Related Pages
JavaScript Reference:document.querySelector()
Other Extensions
Element Object