jQuery filter method: Learn in 13 minutes

The $.filter method

The filter method is used to reduce or filter elements that match the selector or passed the criteria given in the filter jQuery method. For example, in your paragraphs of HTML document (<p>), you want to change the color of only those which class is short_desc.

See example of filter method

Similarly, you have multiple DIV elements in your document and you want to filter and hide only with the class name left_menu.

Syntax of jQuery filter

Following is the basic syntax of jQuery filter method:

.filter( selector/element )

For example

$(“li”).filter(“.midli”)

That means, filter li in the document with class name .midli. After filtering, perform the given action on it.

Similarly,

$(“div”).filter(“.leftmenu”)

This will traverse through the document, find all Div elements and only filter or reduce to those with class name left_menu.

Still confused? See the following example online to learn more about the filter method.

Working example of filter() method of jQuery

In the following example, as the button is clicked, the $.filter method will traverse through the document and find all <p> elements. Next, it will find the .midtext class in <p> tags and change its color to the black.

jQuery filter

Experience this example online

Opposite to the filter method is the not() method. Click here to learn how to use the not() method of jQuery.