HTML | DOM querySelector() Method
The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document.
Note: The querySelector() method only returns first element that match the specified selectors. To return all the matches, use querySelectorAll() method.
Syntax:
element.querySelector(selectors)
Selectors is the required field. It Specifies one or more CSS selectors to match the element. These selectors are used to select HTML elements based on their id, classes, types, etc.
In case of multiple selectors, a comma is used to separate each selector. The element which occurs first in the document is the returned element.
Example:
<!DOCTYPE html> <html> <head> <title>DOM querySelector() Method</title> </head> <body style = "text-align: center;"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>querySelector() Method</h2> <div id="myDIV"> <p>This is paragraph 1.</p> <p>This is pragraph 2.</p> </div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementById("myDIV"); x.querySelector("p").style.backgroundColor = "Green"; x.querySelector("p").style.color = "white"; } </script> </body> </html> |
Output:

After click on the button:

Supported Browsers: The browser supported by querySelector() method are listed below:
- Apple Safari 3.2
- Google Chrome 4.0
- Firefox 3.5
- Opera 10.0
- Internet Explorer 8.0
Recommended Posts:
- HTML | DOM contains() Method
- HTML | DOM getNamedItem() Method
- HTML | DOM click() Method
- HTML | DOM getElementsByName() Method
- HTML | DOM Storage key() Method
- HTML | DOM getAttributeNode() Method
- HTML | DOM insertAdjacentHTML() Method
- HTML | DOM isSameNode() Method
- HTML | DOM cloneNode() Method
- HTML | DOM getBoundingClientRect() Method
- HTML | DOM removeNamedItem() Method
- HTML | DOM insertAdjacentElement() Method
- HTML | DOM getElementsByClassName() Method
- HTML | DOM querySelectorAll() Method
- HTML | DOM execCommand() Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



