Filtering in jQuery with .first(), .last(), .eq(n), .filter(), and .not(). These methods help you select specific elements from a set of matched elements.
1. .first()
$("li").first().css("color", "red");
Effect: Only the first <li> turns red.
2. .last()
$("li").last().css("color", "blue");
Effect: Only the last <li> turns blue.
3. .eq(n)
$("li").eq(1).css("color", "green");
Effect: The second <li> turns green (index 1).
4. .filter()
$("li").filter(".active").css("font-weight", "bold");
Effect: Only <li> elements with class active become bold.
Function example:
$("li").filter(function(index) {
return index % 2 === 0;
}).css("background", "#eee");
Effect: Applies background to even-indexed <li> elements.
5. .not()
$("li").not(".disabled").css("color", "purple");
Effect: All <li> elements without class disabled turn purple.
Quick Summary Table
| Method |
Purpose |
Example |
.first() |
Selects the first element |
$("li").first() |
.last() |
Selects the last element |
$("li").last() |
.eq(n) |
Selects element at index n |
$("li").eq(1) |
.filter() |
Filters elements that match a selector/function |
$("li").filter(".active") |
.not() |
Excludes elements that match a selector/function |
$("li").not(".disabled") |