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.
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");
For more complex logic, you can use filter() and not(). These
methods work like an "If/Else" filter for your selectors.
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");
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");
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");
});
eq() starts counting at
0.
eq(0) = 1st elementeq(1) = 2nd elementeq(4) = 5th element