jQuery .filter() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Subset match

What You’ll Learn

The .filter() traversing method narrows the current jQuery collection to elements matching a selector, passing a callback test, or matching a DOM/jQuery reference. This tutorial covers official div and list demos, function-based filtering by content and index, and compares .filter() with .not() and .find().

01

Selector

.filter(".x")

02

Function

Callback test

03

DOM / jQ

Element match

04

Subset

Not descend

05

vs .not()

Keep vs drop

06

Since 1.0

Core API

Introduction

A jQuery selector often returns more elements than you need — all list items when you only want active ones, every table row when you only want checked checkboxes. The .filter() method narrows that collection to a matching subset without re-querying the DOM.

Available since jQuery 1.0, .filter() accepts a CSS selector string, a callback function, a DOM element, or a jQuery object. Elements that match (or return true from the callback) stay in the result; everything else is excluded.

Understanding the .filter() Method

Given a jQuery object representing a set of DOM elements, .filter(selectorOrFunctionOrElement) tests each element and returns a new jQuery object containing only those that pass. Unlike .find(), it does not search descendants — it only evaluates elements already in the current set.

The callback form receives index and element; this inside the function refers to the current DOM node. Return true to keep the element, false to exclude it.

💡
Beginner Tip

$("li.active") filters at query time. $("li").filter(".active") filters an existing collection — useful when you already have a jQuery object from earlier in a chain.

📝 Syntax

General forms of .filter:

jQuery
.filter( selector )
.filter( function( index, element ) { return trueOrFalse; } )
.filter( element )
.filter( jQueryObject )

Parameters

  • selector — a string containing a selector expression tested against each element in the current set.
  • function — a callback returning true to keep the element; receives index and DOM element; this is the current element.
  • element (since 1.4) — a DOM node; keeps elements matching this node.
  • jQuery object (since 1.4) — keeps elements present in the provided jQuery collection.

Return value

  • A new jQuery object containing the filtered subset of the original matched elements.

Official jQuery API selector example

jQuery
$( "li" ).filter( ":nth-child(2n)" ).css( "background-color", "red" );
// Items 2, 4, 6 — every even DOM child position

⚡ Quick Reference

GoalCode
Keep elements with class$("li").filter(".active")
Custom test per element$("li").filter(function(i, el){ return ...; })
Keep by index condition$("li").filter(function(i){ return i % 3 === 2; })
Match one known element$("div").filter("#unique")
Exclude instead of keep$("li").not(".disabled")
Search descendants (not filter)$("ul").find("li.active")

📋 .filter() vs .not() vs .find()

Three methods that change which elements you work with — different direction and logic.

.filter()
keep match

Subset of current set that matches

.not()
drop match

Subset that does NOT match

.find()
descend

Search inside matched elements

Scope
same set

.filter() never adds new nodes

Examples Gallery

Examples 1–4 follow the official jQuery API documentation. Use DevTools or the Try-it links to run each snippet in the browser.

📚 Getting Started

Official jQuery demos with selector and callback filtering.

Example 1 — Official Demo: Filter by .middle Class

Style all divs green, then add a red border only to those with class middle — official Example 1.

jQuery
$( "div" )
  .css( "background", "#c8ebcc" )
  .filter( ".middle" )
  .css( "border-color", "red" );
Try It Yourself

How It Works

.filter(".middle") runs after all divs get a background. Only divs matching the class remain in the chain for the border style — a classic two-step pattern.

Example 2 — Official Demo: Filter by Content (One <strong>)

Keep list items containing exactly one strong element — official callback demo.

jQuery
$( "li" )
  .filter( function () {
    return $( "strong", this ).length === 1;
  } )
  .css( "background-color", "red" );
Try It Yourself

How It Works

Inside the callback, this is each li. $("strong", this) searches only inside that item. The function returns true when the count equals exactly one.

📈 Practical Patterns

Index-based filtering, combined conditions, and comparison with .not().

Example 3 — Official Demo: Filter by Index Modulo

Highlight every item whose index divided by 3 leaves remainder 2 — items 3 and 6.

jQuery
$( "li" )
  .filter( function ( index ) {
    return index % 3 === 2;
  } )
  .css( "background-color", "red" );
Try It Yourself

How It Works

The index parameter is zero-based position in the unfiltered set. Modulo arithmetic selects repeating positions — similar to .even() but with a custom step.

Example 4 — Official Demo: Index OR id Condition

Filter divs where index is 1 or id is fourth — official Example 2 callback pattern.

jQuery
$( "div" )
  .css( "background", "#b4b0da" )
  .filter( function ( index ) {
    return index === 1 || $( this ).attr( "id" ) === "fourth";
  } )
  .css( "border", "3px double red" );
Try It Yourself

How It Works

Callback filters combine index logic with per-element properties. Any truthy return value keeps the element — logical OR picks multiple unrelated matches.

Example 5 — .filter() vs .not() on the Same List

See how keep-match and drop-match produce opposite subsets.

jQuery
$( "#keep-demo li" ).filter( ".active" ).css( "color", "green" );
$( "#drop-demo li" ).not( ".active" ).css( "color", "gray" );

// Same markup, opposite selection logic
Try It Yourself

How It Works

.filter() and .not() are complements for the same selector. Choose based on whether the matched or unmatched group is smaller or clearer to express.

🚀 Common Use Cases

  • Active tab or menu item$("li").filter(".active").
  • Checked form controls$("input").filter(":checked").
  • Visible elements only$(".panel").filter(":visible").
  • Custom content rules — callback to test text length, child count, or data attributes.
  • Index-based selection — callback with modulo or range logic.
  • Match known element.filter(document.getElementById("x")).

🧠 How .filter() Narrows a Set

1

Start with collection

jQuery object holds matched DOM elements.

Input
2

Test each element

Selector match or callback returns true/false.

Test
3

Collect matches

Only passing elements go into the new set.

Subset
4

Return & chain

New jQuery object — push stack for .end() later.

📝 Notes

  • Available since jQuery 1.0; DOM/jQuery object form since 1.4.
  • Narrows the current set — does not search descendants (use .find()).
  • Callback must return truthy to keep an element; falsy excludes it.
  • With a selector string, text and comment nodes are removed during filtering.
  • Pushes onto jQuery’s internal stack — pair with .end() to restore the previous set.
  • Empty filter result returns an empty jQuery object — safe to chain.

Browser Support

.filter() has been part of jQuery since 1.0+. It relies on selector matching and callback iteration with no browser-specific behavior.

jQuery 1.0+

jQuery .filter()

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. Native equivalent: Array.prototype.filter on a NodeList after conversion.

100% With jQuery loaded
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.filter() Universal

Bottom line: Safe in any jQuery project. Use .filter() to subset collections; use .find() to search inside them.

Conclusion

The jQuery .filter() method narrows a matched collection to elements that pass a selector test, callback function, or element comparison. It is one of the most-used traversing tools for targeting the exact subset you need mid-chain.

Remember the official patterns: selector filtering for classes and pseudos, callback filtering for content and index logic, and .not() when you want the inverse. After filtering, use .end() if the chain needs the previous full set again.

💡 Best Practices

✅ Do

  • Use .filter(".active") to subset an existing collection
  • Use callbacks for rules selectors cannot express
  • Return explicit true / false from filter callbacks
  • Choose .not() when the excluded group is smaller
  • Call .end() after filter when continuing on the original set

❌ Don’t

  • Use .filter() when you need descendant search — use .find()
  • Confuse $("li.active") with $("li").filter(".active") when scope differs
  • Forget that .filter() pushes the selection stack
  • Return non-boolean truthy values unintentionally (e.g. a number)
  • Re-query the DOM when .filter() on the current set suffices

Key Takeaways

Knowledge Unlocked

Five things to remember about .filter()

Keep elements that match.

5
Core concepts
fn 02

Callback

true keeps

Form
# 03

Selector

CSS test

Form
04

.not()

Inverse

Compare
05

Stack

.end() back

Chain

❓ Frequently Asked Questions

.filter() reduces the current jQuery collection to elements that match a CSS selector, pass a callback test, or match a provided DOM element or jQuery object. It returns a new jQuery object containing only the matching subset.
.filter() keeps elements that match the selector or pass the test. .not() removes elements that match — it keeps everything that does NOT match. $('li').filter('.active') keeps active items; $('li').not('.active') keeps inactive ones.
.filter() narrows the current matched set — it only looks at elements already in the collection. .find() searches descendants inside those elements and can return new nodes not in the original set. Use .filter() to subset; use .find() to drill down.
.filter(function(index, element) { ... }) runs the function once per element. If it returns true (or any truthy value), the element stays in the result. Inside the callback, this refers to the current DOM element, and index is the zero-based position in the unfiltered set.
Yes, since jQuery 1.4. .filter(domElement) or .filter($('#unique')) keeps only elements from the current set that are the same node as (or contained in) the argument. Useful when comparing against a known element reference.
No. .filter() only changes which elements the jQuery object refers to. It does not add, remove, or alter DOM nodes — though you may chain methods like .css() or .remove() on the filtered result afterward.
Did you know?

jQuery’s .filter() shares its name with JavaScript’s Array.prototype.filter(), and they work similarly — keep items that pass a test. The jQuery version operates on DOM element collections, pushes onto the internal selection stack (so .end() can restore the pre-filter set), and accepts CSS selectors in addition to callbacks.

Back to jQuery Traversing

Explore more DOM traversal methods as the collection grows.

Traversing hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful