HTML DOM querySelector() Method Examples

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">
    <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() {
            let x = document
                .getElementById("gfg");
            x.querySelector("p")
                .style.backgroundColor = "Green";
            x.querySelector("p").style
                .color ="white";
        }
    </script>
</body>

</html>

Output:

HTML DOM querySelector Method Example

Supported Browsers

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


HTML DOM querySelector() Method

The querySelector() method finds and returns the first HTML element that matches a specific CSS selector. If the selector is invalid, it throws an error.

Use querySelectorAll() to get all matches.

Syntax:

element.querySelector(selectors);

Return value:

Type

Description

Object

is used to return the first element that matches a specified CSS selector(s).

Parameters:

Parameter

Description

CSS Selector

CSS selectors identify HTML elements by id, class, type, attributes, or attribute values. Multiple selectors can be separated by commas.

Similar Reads

HTML DOM querySelector() Method Examples

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