SyntaxStudy
Sign Up
jQuery jQuery .filter() with Functions
jQuery Intermediate 5 min read

jQuery .filter() with Functions

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 true to include, false to 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.

Example
// Keep only list items containing the search term
function filterList(term) {
    $('#results li').hide().filter(function () {
        return $(this).text().toLowerCase().indexOf(term) !== -1;
    }).show();
}
$('#search').on('input', function () {
    filterList($(this).val().toLowerCase());
});

// Keep items with a price above 50
$('#products .item').filter(function () {
    return parseFloat($(this).data('price')) > 50;
}).addClass('premium');

// Keep elements taller than 200 px
$('article').filter(function () {
    return $(this).outerHeight() > 200;
}).addClass('long-read');
Pro Tip

Functional .filter() is the go-to for live search — hide the whole set first, then show the filtered subset.