Open In App

HTML DOM querySelector() Method

Last Updated : 29 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The querySelector() method returns the first element that matches the specified Selector. It only gives one element from the HTML DOM if found else it returns null. To get all the matching elements, you can use the querySelectorAll() method.

Syntax

// To search in complete documemt
ducument.querySelector(selectors);

// To search inside a specific element
element.querySelector("html-tag .class-name #element-id...");

selectors: It is a string containing the CSS Selectors.

Return value: The first element that matches the selectors if found else null.

HTML
<!DOCTYPE html>
<html>
<body style="text-align: center">
    <p>This is paragraph 1.</p>
    <p>This is paragraph 2.</p>

    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {

            // Select the first p element
            let e = document.querySelector("p");

            // Dynamically apply styling 
            // to the first p element
            e.style.backgroundColor = "Green";
            e.style.color = "white";
        }
    </script>
</body>
</html>

Output:

HTML-DOM-querySelector-Example

HTML DOM querySelector Method Example


Next Article
Article Tags :

Similar Reads