While .filter(selector) works well for static criteria, passing a function to .filter() unlocks dynamic, data-driven filtering that no CSS selector can express — comparing element values, checking computed styles, or reading custom data attributes.
Function Signature
The callback receives the index of the current element and the raw DOM node. Return true to keep the element in the set, or false to exclude it. this inside the callback is the raw DOM element — wrap it in $(this) for jQuery methods.
Real-World Examples
Common functional filtering scenarios include keeping only elements with a specific text value, elements whose data attribute exceeds a threshold, or elements that are partially scrolled into the viewport.
- Return
trueto include,falseto exclude - Access index and raw element as arguments
- Combine with
.data(),.text(),.attr()inside the function - Chain
.filter(fn)with other traversal and styling methods
Unlike client-side search with hidden/visible toggling, functional filtering operates on jQuery sets in memory and does not change the DOM, so it is safe to use as a pre-step before deciding what to show or animate.