English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery filter() method

jQuery Traversal Methods

The filter() method returns elements that match specific conditions.

The filter() method filters out all elements that do not match the selected conditions and returns those that match.

The filter() method is similar tonot()The opposite method.

Syntax:

Get elements that match specific conditions:

$(selector).filter(criteria)

Use a function to get elements:

$(selector).filter(function(index))

Example

Return all paragraphs with class name "demo":

$("document").ready(function(){
  $("p").filter(".demo").css("background", "coral");
});
Test to see‹/›

Return all even items:

$("document").ready(function(){
  $("li").filter(":even").css("background", "coral");
});
Test to see‹/›

Change the color of all divs; then add a border style for users with the "middle" class:

$("document").ready(function(){
  $("div").css("background", "#c8ebcc").filter(".middle").css("border-color", "red");
});
Test to see‹/›

Use a function to filter out elements:

$("document").ready(function(){
  $("div").filter(function(i){  
        return $(this).hasClass("middle");
  }).css("background-color", "blue");
});
Test to see‹/›

Parameter Value

ParameterDescription
criteriaSpecify a selector expression, a jQuery object, or one or more elements returned from a set of selected elements.
To specify multiple conditions, use commas
function(index)Specify a function to be used to test each element in the collection
  • index-Return the index position of the element in the collection

jQuery Traversal Methods