jQuery filter() Method

The jQuery is a very powerful tool which helps us to incorporate a variety of DOM traversal methods to select elements in a document randomly or in sequential order. Most of the DOM traversal methods do not modify the elements whereas they filter them out upon the given conditions.
The filter() method is used to filter out all the elements that do not match the selected criteria and those matches will be returned.
Syntax:

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

Parameters:
criteria : It specifies a selector expression, a jQuery object or one or more elements to be returned from a group of selected elements.
function(index) : It specifies a function to run for each element in the set. If the function returns true, the element is kept. Otherwise, it is removed.
index : The index position of the element in the set.
NOTE : To specify more than one criteria, use a comma.

jQuery code to show the working of the filter() method

Code #1:




<html>
  
<head>
    <title>Beginner FOR Beginner ARTICLE</title>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("li").filter(".first, .last").css("color", "red")
                .css("backgroundColor", "yellow");
        });
    </script>
</head>
  
<body>
    <ul>
        <li class="first">w3wiki</li>
        <li class="first">w3wiki</li>
        <li class="middle">w3wiki</li>
        <li class="last">w3wiki</li>
        <li class="last">w3wiki</li>
    </ul>
</body>
  
</html>


Output:

Code #2:
This code will select the elements matching with the criteria checked by the function. Here, the function checks for two elements in a list and returns true or false.




<html>
  
<head>
    <title>Beginner FOR Beginner ARTICLE</title>
    <script src="https://ajax.googleapis.com/ajax/libs/
                 jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("ul").filter(function() {
                return $("li", this).length == 2;
            }).css("color", "red").css("fontSize", "20");
        });
    </script>
</head>
  
<body>
    A list with two elements:
    <ul>
        <li>option1</li>
        <li>option2</li>
    </ul>
    A list with one element:
    <ul>
        <li>option1</li>
    </ul>
    A list with two elements:
    <ul>
        <li>option1</li>
        <li>option2</li>
    </ul>
    A list with three elements:
    <ul>
        <li>option1</li>
    </ul>
    <ul>
        <li>option2</li>
    </ul>
    <ul>
        <li>option3</li>
    </ul>
</body>
  
</html>


Output:



Contact Us