HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Filtering

Filtering allows you to narrow down a search from a group of elements based on their position or specific criteria. Think of it as a "refinement" step that happens after you make a general selection. This gives you surgical precision when manipulating the DOM.


Basic Filtering Methods

The three most basic filtering methods allow you to select elements based on their **position** in the group.

Method What it returns...
first() The first element in the current group.
last() The last element in the current group.
eq(index) The element at a **specific index** (starting from 0).
// Target the FIRST paragraph
$("p").first().css("font-weight", "bold");

// Target the THIRD list item (index 2)
$("li").eq(2).addClass("active");

Logic-Based Filtering

For more complex logic, you can use filter() and not(). These methods work like an "If/Else" filter for your selectors.

1. The filter() Method

Returns only the elements that match your specified criteria. Any element that does not match is excluded.

// Returns only <p> elements with the class "intro"
$("p").filter(".intro");

2. The not() Method

This is the opposite of filter(). it returns elements that **do NOT** match the criteria.

// Returns all <p> elements EXCEPT those with class "intro"
$("p").not(".intro");

Practical Example: Alternating Styles

While CSS has :nth-child, filtering in jQuery allows you to perform complex actions (like animations) on specific segments of a list.

$("#btn").click(function() {
    // Select all items, but filter out the 'header' item
    $("li").not(".list-header").fadeOut("slow");
    
    // Highlight only the last item of the remaining visible list
    $("li").last().css("background", "yellow");
});
Zero-Based Indexing: remember that eq() starts counting at 0.
  • eq(0) = 1st element
  • eq(1) = 2nd element
  • eq(4) = 5th element

Key Points to Remember

  • first() and last() target the ends of a collection.
  • eq() is the most flexible way to target a single item by its position number.
  • filter() keeps matches; not() removes matches.
  • Filtering can be used on any jQuery collection, including results from traversing methods.
  • Use these methods to avoid adding repetitive IDs or classes to every single HTML element.