Open In App

jQuery querySelector() Vs querySelectorAll() Methods

Improve
Improve
Like Article
Like
Save
Share
Report

querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors (‘id’, ‘class’) can be selected.

querySelector() Method: The querySelector() method returns the first element within the document which matches a specified CSS selector(s). If multiple elements occurs, then it returns the result for only the first matching element.

Syntax:

document.querySelector(selectors);

It returns the first element which matches the selector.

querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s). It returns all the elements that matches with the selector in the form of a static NodeList object which is a collection of nodes. To access each element, we usually use a loop. Each element can be accessed via an index. The index starts with 0. The property length can be used to get the number of elements that matches the specified selector.

Syntax:

document.querySelectorAll(selectors);

It returns all the elements which match the selector.

document.querySelectorAll(selectors)[i];

It returns the element at index i in the list.

Difference between querySelector() and querySelectorAll() Method:

HTML code:

HTML




<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
  
    <h1 style="color:#006600">
        GeeksforGeeks
    </h1>
  
    <div class="test-btn">text</div>
    <div class="test-btn">text</div>
    <div class="test-btn">text</div>
    <div class="test-btn">text</div>
  
    <button onClick="qselector()">
        querySelector
    </button>
  
    <button onClick="qselectorall()">
        querySelectorAll
    </button>
  
    <script>
        function qselector() {
            document.querySelector(".test-btn")
                .style.color = "#006600";
        }
  
        function qselectorall() {
            var x = document
                .querySelectorAll(".test-btn");
  
            for (var i = 0; i < x.length; i++) {
                x[i].style.color = "#006600";
            }
        
    </script>
</body>
  
</html>


Output:

  • Before clicking any button:
  • After clicking querySelector button:
  • After clicking querySelectorAll button:

Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.



Last Updated : 23 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads