jQuery filter() Method

The jQuery filter() method can be used to return the element matching with certain criteria. It also filters out the elements that are not matching the specified criteria.

jQuery filter() Method

Syntax

The syntax of this method is given below:-

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

Description of the Parameters

The description of these parameters is given below.

Parameter Name Description
selector Specify the element to select and filter the element at certain criteria. You can use the element tag name, class name, or id to select. It is a required field.
criteria You have to specify an expression, jQuery objects, or one or more elements to be returned from the selected group element.
index It is the index position of the element to select.

jQuery filter() Method Filter Single Element

If you want to return the single element by filtering the other elements, you have to use the method as given below. The example contains the button and the list elements. You have to filter out other elements and select only the first element.

Example

Test it Live

Output

  • PHP
  • SQL
  • Python
  • jQuery


When you click the button given above, it selects the first element and apply the yellow color to it. The above example also using the css() method to apply CSS.

Filter Multiple Element Using jQuery filter() Method

If you want to filter multiple items of a group element, you have to use the method as given below. The example returns two elements of the list and apply CSS.

Example

Test it Live

Output

  • First
  • Second
  • Third
  • Last


You have to click the button given above to select two elements using the method. It applies the orange color to the first and last element of the list.

Use Function to Filter Element

The jQuery filter() method can also be used with the function to filter the elements. Use the function with the method as given in the example below.

Example

Test it Live

Output

  • First
  • Second
  • Third
  • Last
  • First
  • Second
  • Last
  • First
  • Second
  • Third
  • Last


Click the button given above to select the list element that contains only two list items. The above example applies the red color to the list element and its items.

You may also like to read

I hope you like this tutorial on jQuery filter() method. If you have any queries regarding the tutorial, please comment below.

References