How to Use jQuery filter() with a Selector
This article provides an overview and practical guide on using
jQuery's .filter() method to reduce a collection of matched
elements using a selector. You will learn the correct syntax, see
practical examples demonstrating class- and attribute-based filtering,
and understand the key difference between .filter() and
child-traversal methods like .find().
Basic Syntax
The .filter() method evaluates each element in the
current jQuery object against a specified selector string and constructs
a new jQuery object containing only the elements that match.
$(selector).filter(targetSelector);selector: The initial set of elements you select from the DOM.targetSelector: A string containing a selector expression (such as a class, ID, attribute, or pseudo-class) used to test each element in the initial set.
Filtering by Class
The most common use case is filtering an existing list of elements by a CSS class.
Given the following HTML:
<ul>
<li class="item">Item 1</li>
<li class="item active">Item 2</li>
<li class="item">Item 3</li>
<li class="item active">Item 4</li>
</ul>You can target all <li> elements and filter down
to only those with the .active class:
// Selects only Item 2 and Item 4
$('li').filter('.active').css('background-color', 'yellow');Filtering by Attributes and Pseudo-Selectors
You can pass any valid CSS or jQuery selector string into
.filter(), including attribute selectors and
pseudo-classes.
Attribute Selector Example
// Matches only text inputs among all input elements
$('input').filter('[type="text"]').addClass('text-field');Pseudo-Selector Example
// Matches only visible paragraph elements
$('p').filter(':visible').fadeIn();
// Matches even-indexed elements from a list
$('li').filter(':even').addClass('striped');Using Multiple Selectors
You can pass multiple comma-separated selectors to
.filter() to match elements meeting any of the specified
criteria.
// Matches list items that have either the .highlight or .selected class
$('li').filter('.highlight, .selected').css('font-weight', 'bold');filter() vs.
find()
It is important not to confuse .filter() with
.find():
.filter()checks the elements already present in your current jQuery selection. It does not look down the DOM tree..find()searches the descendants (children, grandchildren, etc.) of the elements in your current selection.
// Given: <div class="container"><span class="highlight">Text</span></div>
// Returns the <div> if the div itself has the class .highlight (returns empty here):
$('div').filter('.highlight');
// Returns the <span> inside the <div>:
$('div').find('.highlight');