Skip to content
Related Articles

Related Articles

Improve Article

What’s the difference between selector and filter() in jQuery?

  • Last Updated : 12 Apr, 2021

jQuery Selectors: allow us to select and manipulate HTML element(s). It is used to select HTML elements such as ids, classes, types, attributes, etc using jQuery selectors and then add any CSS properties or events to the selected HTML elements.

Syntax: For selecting a button tag the syntax would be

$("button") 

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("#heading").css("border", "2px solid red");
            });
        });
    </script>
</head>
  
<body>
  
    <h2 id="heading">Using jQuery Filter</h2>
  
    <button>Click to change color of heading</button>
  
</body>
  
</html>

Output: On clicking the button, we will see a red border across the heading.

Clicking button creates border across heading       

jQuery Filter: This method is used to specify criteria for an HTML element. Filter() method returns elements that match certain criteria.



Syntax:

$(selector).filter(criteria, function(index))

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function() {
            $("p").filter(".active").css("background-color", "red");
        });
    </script>
</head>
  
<body>
  
    <h1>Jquery Filter</h1>
  
      
<p>My name is Donald.</p>
  
    <p class="active">Geeks</p>
  
    <p class="dead">SkeeG</p>
  
    <p class="active">For </p>
  
    <p class="dead">roF</p>
  
    <p class="active">Geeks</p>
  
</body>
  
</html>

Output: filter searches out the active class tags and colors them.

 Filters active class               

Major differences between selector and filter() in jQuery:

          Selector in jQuery                                            filter() n jQuery
jQuery selector selects all elements based on the elements name given by you.jQuery filter( ) adds further detail to the selected elements by specifying the criteria of selection.
It works independently of filter( ), which means there is no need to use it along with the filter( ) method.It works along with the selector. By combining filters with your selectors, we can work to much high degree of precision.

Syntax to use it is as follows:

   $(“button”) selects all buttons of the HTML page.

Syntax to use it as follows:

$(button).filter(criteria, function(index)) selects buttons having criteria and applies function on it. 




My Personal Notes arrow_drop_up
Recommended Articles
Page :