← Back to Chapters

jQuery Traversing – Filtering

? jQuery Traversing – Filtering

✨ Quick Overview

Filtering methods let you refine a set of elements by selecting specific ones based on conditions.

? Key Concepts

  • filter() – Keeps only elements that match conditions
  • not() – Removes elements from the matched set
  • eq() – Selects element by index
  • first() – Picks the first matched element
  • last() – Picks the last matched element
  • has() – Selects elements containing a child

? Syntax / Theory

? View Code Example
// jQuery filtering method syntax
$(selector).filter(selector|function);
$(selector).not(selector|function);
$(selector).eq(index);
$(selector).first();
$(selector).last();
$(selector).has(selector);

? Interactive Example

Red Box
Green Box
Blue Box
Another Green Box
Another Red Box
Contains Span No Color

? Live Code Playground

Type jQuery code below to filter the list items (e.g., .filter(':even') or .eq(1)):

  • Item 0
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5
$('#playList li')

? Code Explanation

? View Code Example
// Select and filter green boxes
$('#filterContainer .box').filter('.color-green');

// Exclude green boxes
$('#filterContainer .box').not('.color-green');

// Select third box using zero-based index
$('#filterContainer .box').eq(2);

// Select first and last boxes
$('#filterContainer .box').first();
$('#filterContainer .box').last();

// Select boxes containing a span element
$('#filterContainer .box').has('span');

? Use Cases

  • Highlighting search results dynamically
  • Filtering lists and grids
  • Conditional UI styling
  • Interactive dashboards

✅ Tips & Best Practices

  • Remember that eq() uses zero-based indexing
  • Use has() when DOM structure matters
  • Reset styles when chaining multiple demos

? Try It Yourself

  • Use a function inside filter()
  • Combine filter() and not()
  • Filter elements based on text length