Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML DOM querySelector() method

HTML DOM querySelector() method

HTML Element Object Reference Element object

Example

Modify the element with class="demo"

The text content of the first child element:

var

x

=

document

.

getElementById

(

"

myDIV

"

)

;

x

.

querySelector

(

"

.demo

"

)

.

innerHTML

=

"

Hello World!

"

;

Try it »

Definition and usage

The querySelector() method returns the first child element that matches the specified CSS selector.

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 our CSS Selector Tutorial and our CSS Selector Reference Manual.


Browser support

The numbers in the table indicate the first browser version that supports this method.

Method
querySelector() 4.0 8.0 3.5 3.1 10.0

Syntax

element

.querySelector(

CSS selector

)

Parameter value

Parameters Type Description
CSS selector String Required. One or more CSS selectors that match elements. You can use their id, class, type, attribute, attribute value, etc. to select elements.
 对于多个选择器,使用逗号隔开,返回一个匹配的元素。       

   

 Hint: More CSS selectors, See also our [CSS Selector Reference Manual](/cssref/css-selectors.html).

Technical Details

DOM version: Selectors Level 1 Element Object
Return value: The first element that matches the specified CSS selector. If not found, returns null. If an invalid selector is specified, a SYNTAX_ERR exception is thrown.

More examples

Example

Modify

The first element in the

element content:

var x = document.getElementById("myDIV");

x.querySelector("p").innerHTML = "Hello World!";

Try it »

Example

Modify

The content of the first child element with class="example" in the element:

var x = document.getElementById("myDIV");

x.querySelector(".example").innerHTML = "Hello World!";

Try it »

Example

Modify

The first child element with class="example" in the element

element:

var x = document.getElementById("myDIV");

x.querySelector("p.example").innerHTML = "Hello World!";

Try it »

Example

is

The first element with the target attribute in the element Add a red border:

var x = document.getElementById("myDIV");

x.querySelector("a[target]").style.border = "10px solid red";

Try it »

Example

The following example demonstrates the use of multiple selectors.

Suppose you select two selectors:

and

.

The following code will set the background color for the