jQuery filter() Method

You are Here:

jQuery filter() Method

The jQuery filter() method returns elements that match the selector or pass the function's test.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery filter() Method</h1> <p>This is paragraph1</p> <div style="border: 1px solid black;"> <p class="point">This is paragraph2</p> <p>This is paragraph3</p> </div> <p>This is paragraph4</p> <script> $(document).ready(function(){ $("div p").filter(".point").css("color", "red"); }); </script> </body> </html>

Syntax

$(selector).filter(selector); // or $(selector).filter(callback);

Parameter Values

ValueTypeExplanation
selectorRequiredSpecifies a selector for filter.
callbackRequiredSpecifies a function to be called every time an element / selector matches.

filter() with selector

In the following example, we will filter out all the even <li> elements by using :even selector.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1 class="point">jQuery filter() Method</h1> <ul> <li>Apple</li> <li>Banana</li> <li>Mango</li> </ul> <script> $(document).ready(function(){ $("ul li").filter(":even").css("color", "red"); }); </script> </body> </html>

filter() with function

In the following example, we will filter the elements which pass the function's test.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1 class="point">jQuery filter() Method</h1> <ul> <li>Apple</li> <li>Banana</li> <li>Cheery</li> <li>Dragon fruit</li> <li>Elderberry</li> <li>fig</li> <li>Grapes</li> <li>Honeydew</li> </ul> <script> $(document).ready(function(){ $("ul li").filter(function(index){ if(index % 3 == 0){ $(this).css("color","red"); } }); }); </script> </body> </html>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author