DOM querySelector() Method

 


Definition and Usage

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.


Syntax

document.querySelector(CSS selectors)

Parameter Values

ParameterTypeDescription
CSS selectorsStringRequired. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc.

For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document (See "More Examples").

        <!DOCTYPE html>
    <html>
        <body>

        <p>This is a p element.</p>

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

        <script>
            function myFunction() {
                document.querySelector("p").style.backgroundColor = "red";
            }
        </script>

        </body>
    </html>