jQuery filter() Method

Last Updated:

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
selector Required Specifies a selector for filter.
callback Required Specifies a function to be called every time an element / selector matches.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
filter()YesYesYesYesYesYesYesYesYesYesYesYesYes

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>

Share this Page

Meet the Author