jQuery - Filtering in jQuery

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()

  • Selects the first element from the matched set.

$("li").first().css("color", "red");

Effect: Only the first <li> turns red.


2. .last()

  • Selects the last element from the matched set.

$("li").last().css("color", "blue");

Effect: Only the last <li> turns blue.


3. .eq(n)

  • Selects the element at index n (0-based) from the matched set.

$("li").eq(1).css("color", "green");

Effect: The second <li> turns green (index 1).


4. .filter()

  • Reduces the set of matched elements to those that match a selector or satisfy a function.

$("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()

  • Excludes elements that match a selector or criteria from the matched set.

$("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")