JavaScript’s Document.querySelector()
method returns the first element that matches any of the specified CSS selectors or null
if no element matches the selectors.
Syntax
Document.querySelector(parameter);
Parameters
A string containing one or more CSS selectors to match.
Return value
An Element
object or null
if no element matches the selectors.
Please note that the querySelector()
method returns a single matching element, whereas the querySelectorAll()
method returns a list of all matching elements.
Exceptions
SyntaxError
DOMException
Thrown if the parameter cannot be parsed as a CSS selector list.
Examples
Here are some examples of using the JavaScript querySelector()
method.
Suppose we have the following HTML elements:
<div id="welcomeText">
<p>Welcome to the <a href="https://javascriptguide.com">JavaScript Guide</a>!</p>
</div>
How can we select the p
element?
We can use the querySelector()
method:
let p = document.querySelector('p');
However, a better selector would include the id
of the p
element’s parent element:
let p = document.querySelector('#welcomeText p');
That is because id
attributes are unique identifiers. By using them, we can be sure that we select the right element.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
querySelector() |
1 | 12 | 3.5 | 8 | 10 | 3.1 | 18 | 4 | 10.1 | 2 | 1.0 | 4.4 |