Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

HTML DOM querySelector() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method.

Syntax:

element.querySelector(selectors);

Selectors are 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 the case of multiple selectors, a comma is used to separate each selector. The element which occurs first in the document is the returned element. If the selector matches an id( which should be unique on each page), which is used several times in the document then it will return the first matching element.

Return value :- This method  is used to return the first element that matches a specified CSS selector(s) in the document.

Example: This example describes the use of the DOM querySelector() method to select the very first matching element for the specific selector.

HTML




<!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="gfg">
         
 
<p>This is paragraph 1.</p>
 
 
         
 
<p>This is paragraph 2.</p>
 
 
    </div>
    <button onclick="myFunction()">Try it</button>
    <script>
    function myFunction() {
        var x = document.getElementById("gfg");
        x.querySelector("p").style.backgroundColor = "Green";
        x.querySelector("p").style.color = "white";
    }
    </script>
</body>
 
</html>

Output:

DOM querySelector() Method

Supported Browsers: The browser supported by querySelector() method are listed below:

  • Google Chrome 1
  • Edge 12
  • Internet Explorer 9
  • Firefox 3.5
  • Opera 10
  • Safari 3.1

My Personal Notes arrow_drop_up
Last Updated : 13 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials