HTML | DOM querySelectorAll() Method

The querySelectorAll() method in HTML is used to return a collection of an element’s child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Note: If we want to apply CSS property to all the child nodes that match the specified selector, then we can just iterate through all nodes and apply that particular property.

Syntax:

element.querySelectorAll(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, comma is used to separate each selector.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>DOM querySelectorAll() Method</title>
        <style>
            #geek {
              border: 1px solid black;
              margin: 5px;
            }
        </style>
    </head>
    <body style = "text-align: center;">
        <h1 style = "color: green;">GeeksforGeeks</h1>
        <h2>querySelectorAll() Method</h2>
        <div id="geek">
            <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").querySelectorAll("p");
                var i;
                for (i = 0; i < x.length; i++) {
                x[i].style.backgroundColor = "green";
                x[i].style.color = "white";
                }
            }
        </script>
    </body>
</html>

chevron_right


Output:
queryselectorall1

After clicking the button:
queryselectorall2

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 9.0


My Personal Notes arrow_drop_up


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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.