SyntaxStudy
Sign Up
jQuery jQuery Filtering Introduction
jQuery Beginner 4 min read

jQuery Filtering Introduction

After selecting a set of elements, you often want to narrow that set — keeping only elements that meet certain criteria. jQuery's filtering methods let you refine selections without writing new, more complex selectors. They are faster and more readable because they operate on an already-retrieved set.

The Filtering Family

jQuery provides a rich set of filtering methods: .filter() to keep matches, .not() to exclude matches, .has() to keep elements that contain a specific descendant, .is() to test the entire set, and index-based filters like .first(), .last(), and .eq().

Selectors vs Filtering Methods

Complex CSS selectors applied to the whole document can be slow on large pages. Building your query in two stages — a broad selector to retrieve a manageable set, then a filtering method to narrow it — is often faster and always more readable.

  • .filter(selector) — keep only matching elements
  • .not(selector) — exclude matching elements
  • .has(selector) — keep elements with a matching descendant
  • .is(selector) — returns true/false, does not filter
  • .first(), .last(), .eq(n) — index-based selection
Example
// All paragraphs, then filter to those with class "highlight"
var $highlighted = $('p').filter('.highlight');

// Exclude disabled inputs
$('input').not(':disabled').val('');

// Keep list items that contain a link
$('li').has('a').addClass('has-link');

// Test if a selection matches (returns boolean)
if ($('#form').is(':visible')) {
    console.log('Form is visible');
}

// Index-based
$('tr').first().addClass('table-head');
$('tr').last().addClass('table-foot');
$('tr').eq(2).addClass('third-row'); // zero-based
Pro Tip

Filter an already-retrieved set with .filter() rather than re-querying the DOM with a new complex selector.