Returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.
Syntax
element = baseElement.querySelector(selectors);
Examples
In this example, the first style element which either has no type or has type text/css in the HTML document body is returned:
var el = document.body.querySelector("style[type='text/css'], style:not([type])");
The following example demonstrates that selectors is first applied to the whole document, not baseElement. The "div span" selector matches the span element, despite the <div> element not being a descendant of the baseElement. The result is "inside span":
<div>
<p>
inside paragraph
<span>inside span</span>
inside paragraph
</p>
</div>
<script>
var baseElement = document.querySelector("p");
console.log(baseElement.querySelector("div span").innerHTML);
</script>
Notes
Returns null if no matches are found; otherwise, it returns the first matching element.
Throws a SYNTAX_ERR exception if the specified group of selectors is invalid.
querySelector() was introduced in the WebApps API.
The string argument passed to querySelector() must follow CSS syntax. See document.querySelector for concrete examples.
selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are child-elements of baseElement. The first such element is returned.
Specifications
| Specification | Status | Comment |
|---|---|---|
| DOM4 The definition of 'querySelectorAll' in that specification. |
Working Draft | |
| Selectors API Level 2 The definition of 'querySelectorAll' in that specification. |
Working Draft | |
| Selectors API Level 1 The definition of 'querySelectorAll' in that specification. |
Recommendation |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 1 |
3.5 (1.9.1) |
9 [1] |
(Yes) |
(Yes) |
| Feature | Android | Firefox Mobile (Gecko) | Firefox OS (Gecko) | IE Phone | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
[1] querySelector() is supported in IE8, but only for CSS 2.1 selectors.