Easy Tutorial
❮ Prop Fileupload Disabled Event Onseeked ❯

HTML DOM querySelector() Method

Document Object

Example

Get the element with id="demo" in the document:

document.querySelector("#demo");

Definition and Usage

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

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

For more CSS selectors, visit our CSS Selectors Tutorial and our CSS Selectors Reference.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method Chrome IE Firefox Safari Opera
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. These can be the element's id, class, type, attribute, attribute value, and more. <br> <br>For multiple selectors, separate them with commas and it will return the first matching element. <br> <br> Tip: For more CSS selectors, refer to our CSS Selectors Reference

Technical Details

DOM Version: Selectors Level 1 Document Object
Return Value: The first element that matches the specified CSS selector. <br> If no matches are found, it returns null. If an invalid selector is specified, it throws a SYNTAX_ERR exception.
--- ---

More Examples

Example

Get the first <p> element in the document:

document.querySelector("p");

Example

Get the first element with class="example":

document.querySelector(".example");

Example

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

document.querySelector("p.example");

Example

Get the first <a> element with a "target" attribute:

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

Example

The following example demonstrates the use of multiple selectors.

Assume you have selected two selectors: <h2> and <h3> elements.

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

<h2>A h2 element</h2><h3>A h3 element</h3>
<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>

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

<h3>A h3 element</h3><h2>A h2 element</h2>
<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>

Related Pages

JavaScript Reference: element.querySelector()


Document Object

❮ Prop Fileupload Disabled Event Onseeked ❯