JavaScript - querySelectorAll() method

revision:


Category : document

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

The querySelectorAll() method returns all elements that matches a CSS selector(s). It returns a NodeList and throws a SYNTAX_ERR exception if the selector(s) is invalid.

Syntax :

        querySelectorAll(selectors)
    

Parameters:

selectors : required. A string containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. Multiple selectors may be specified by separating them using commas.

Examples:

            const matches = document.querySelectorAll("p");
            const matches = document.querySelectorAll("div.note, div.alert");
            const container = document.querySelector("#test");
            const matches = container.querySelectorAll("div.highlighted > p");            
            const matches = document.querySelectorAll("iframe[data-src]");
            const container = document.querySelector("#userlist");
            const matches = container.querySelectorAll("li[data-active='1']");

            const highlightedItems = userList.querySelectorAll(".highlighted");
            highlightedItems.forEach((userItem) => {
                deleteUser(userItem);
            });
        

Category: element

The Element method querySelectorAll() returns a tatic (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.

Syntax :

        querySelectorAll(selectors)
    

Parameters:

selectors : a string containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a "SyntaxError exception" is thrown. Multiple selectors may be specified by separating them using commas. Note that the selectors are applied to the entire document, not just the particular element on which querySelectorAll() is called. To restrict the selector to the element on which querySelectorAll() is called, include the "":scope pseudo-class" at the start of the selector.

Examples:

            <section class="box" id="sect1">
                <div class="funnel-chart-percent1">10.900%</div>
                <div class="funnel-chart-percent2">3700.00%</div>
                <div class="funnel-chart-percent3">0.00%</div>
            </section>
            <script>
                // dataset selectors
                const refs = [
                ...document.querySelectorAll(`[data-name*="funnel-chart-percent"]`),
                ];

                // attribute selectors
                // const refs = [...document.querySelectorAll(`[class*="funnel-chart-percent"]`)];
                // const refs = [...document.querySelectorAll(`[class^="funnel-chart-percent"]`)];
                // const refs = [...document.querySelectorAll(`[class$="funnel-chart-percent"]`)];
                // const refs = [...document.querySelectorAll(`[class~="funnel-chart-percent"]`)];
            </script>

            const matches = myBox.querySelectorAll("p");
            const matches = myBox.querySelectorAll("div.note, div.alert");
            const container = document.querySelector("#test");
            const matches = container.querySelectorAll("div.highlighted > p");
            const matches = document.querySelectorAll("iframe[data-src]");

            const container = document.querySelector("#userlist");
            const matches = container.querySelectorAll("li[data-active='1']");
        

Practical examples

example: selector scope
.outer
.subject
.inner

            
code:
                    <div>
                        <button id="select">Select</button>
                        <button id="select-scope">Select with :scope</button>
                        <div id="outer">
                            .outer
                            <div id="subject">
                                .subject
                                <div id="inner">.inner</div>
                            </div>
                        </div>
                        <pre id="output"></pre>
                    </div>
                    <script>
                        const subject = document.querySelector("#subject");
                        const select = document.querySelector("#select");
                        select.addEventListener("click", () => {
                            const selected = subject.querySelectorAll("#outer #inner");
                            output.textContent = `Selection count: ${selected.length}`;
                        });
            
                        const selectScope = document.querySelector("#select-scope");
                        selectScope.addEventListener("click", () => {
                        const selected = subject.querySelectorAll(":scope #outer #inner");
                            output.textContent = `Selection count: ${selected.length}`;
                        });
                        
                    </script>
                

example: select all elements with class="example"

Add a background color all elements with class="example":

A heading

A paragraph.

Another paragraph.

A div element

this is a special paragraph with span having classname "example"

this is a special paragraph with span having classname "one"

code:
                    <div>
                        <p>Add a background color all elements with class="example":</p>
                        <h4 class="example">A heading</h4>
                        <p class="example">A paragraph.</p> 
                        <p class="one">Another paragraph.</p> 
                        <div class="one">A div element </div>
                        <p>this is a <span class="example">special</span>paragraph with span having classname "example"</p>
                        <p>this is a <span class="one">special</span>paragraph with span having classname "one"</p>
                        <p id="query-1"></p>
                        <p id="query-2"></p>
                    </div>
                    <script>
                        const nodeList = document.querySelectorAll(".example");
                        for (let i = 0; i < nodeList.length; i++) {
                            nodeList[i].style.backgroundColor = "red";
                        }
                        const nodeList1 = document.querySelectorAll(".one");
                        for (let j = 0; j < nodeList1.length; j++) {
                            nodeList1[j].style.color = "blue";
                        }
                        document.getElementById("query-1").innerHTML = " number of elements with class='example' : " + nodeList.length;
                        document.getElementById("query-2").innerHTML = " number of elements with class='one' : " + nodeList1.length;
                    </script>
                

example: set the border style of all <a> elements in a <div> element that have a "target" attribute.

Click the button to add a red border to all links in DIV that have a target attribute.

code:
                    <div>
                        <div id="DIV-B">
                            <a href="https://www.lwitters.com">my website.com</a><br><br>
                            <a href="http://www.disney.com" target="_blank">disney.com</a><br><br>
                            <a href="http://www.wikipedia.org" target="_top">wikipedia.org</a>
                        </div>
                        <p>Click the button to add a red border to all links in DIV that have a target attribute.</p>
                        <button onclick="queryFunction()">Try it</button>
                    </div>
                    <style>
                        a[target] {background-color: yellow;}            
                    </style>
                    <script>
                        function queryFunction() {
                            var x = document.getElementById("DIV-B").querySelectorAll("a[target]");
                            var i;
                            for (i = 0; i < x.length; i++) {
                                x[i].style.border = "10px solid red";
                            }
                        }
                    </script>