Javatpoint Logo
Javatpoint Logo

jQuery filter()

The filter() method returns the elements matching the specified criteria. If elements do not match the criteria, they are removed from the selection.

It can take a selector or a function as its arguments for filtering the set of matched elements. When using selector, the method filters the elements don't match the given selector. If we use function, the method filters the elements that don't match the given function. Generally, this method is used to reduce the search for an element in the set of selected elements.

Syntax

Using selector

Using function

The parameter values of this function are defined as follows.

selector: It is an optional attribute. It could be a JQuery object or a selector expression. We can also use the comma-separated list of expressions to apply multiple filters at once. It can be written as follows:

function: It is also an optional parameter. This parameter specifies a function that runs for every element in the group. The element is kept if the function returns true. Otherwise, on returning false, the element is removed.

The index argument represents the position of the element in the set. It begins with the 0 position.

Let's see some examples to understand how to use the filter() method.

Example1

In this example, we are using the selector attribute of the filter() function. Here, the filter() function returns all paragraph elements with class name para. There are some div elements, paragraph elements and others. There are three paragraph elements out of four related to the class para.

We have to click the given button to see the result.

Test it Now

Output

jQuery filter()

After clicking the button, we can see that the function returns the paragraph elements related to the class name para.

jQuery filter()

Example2

In this example we are using the function(index) parameter of the filter() function.. Here, the function highlights the paragraph elements with index position 1, 3, and 5. Because the index begins with 0 so, it highlights the paragraph on even position.

Test it Now

Output

After the execution of the above code, the output is -

jQuery filter()

After clicking the given button, we can see that the function return the paragraph elements with index positions 1, 3, and 5. The position of the index starts at 0.

jQuery filter()





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA