Episode 6 of 24

jQuery Filters

Learn jQuery filter methods to narrow down your selections.

Filters let you refine your selection to target specific elements within a matched set.

Position Filters

$("li:first")          // First <li> element
$("li:last")           // Last <li> element
$("li:eq(2)")          // Third <li> (0-indexed)
$("li:lt(3)")          // First three <li> elements
$("li:gt(1)")          // All <li> after the second
$("li:even")           // Even-indexed <li> elements
$("li:odd")            // Odd-indexed <li> elements

Content Filters

$("p:contains('hello')")     // Paragraphs containing "hello"
$("div:has(p)")              // Divs that contain a <p>
$("td:empty")                // Empty table cells
$("td:parent")               // Table cells with content

Visibility Filters

$("div:visible")       // Visible divs
$("div:hidden")        // Hidden divs

Filter Methods

// .filter() — keep elements that match
$("li").filter(".active").css("color", "green");

// .not() — exclude elements that match
$("li").not(".disabled").css("cursor", "pointer");

// .first() and .last()
$("p").first().css("font-weight", "bold");
$("p").last().css("font-style", "italic");

// .eq() — select by index
$("li").eq(2).css("background", "#eee");

// .slice() — select a range
$("li").slice(1, 4).css("color", "blue");

Chaining Filters

$("li")
    .filter(":even")
    .css("background", "#f5f5f5")
    .end()            // Go back to original selection
    .filter(":odd")
    .css("background", "#e0e0e0");