jQuery Filters

Filters in jQuery allow a broad selection to be narrowed down to specific elements based on their position, content, visibility, or type. They are used as part of selectors or as chained traversal methods to precisely target the elements needed.

What are Filters?

When a selector like $("li") is used, every <li> on the page is selected. Filters help target a subset — for example, only the first item, only items with specific text, or only currently visible items.

Filters can be applied in two ways:

  • Selector filters: Written in the selector string (e.g., $("li:first"))
  • Method filters: Chained as a method (e.g., $("li").first())

Basic Filters

$("tr:first")          // First table row
$("tr:last")           // Last table row
$("tr:even")           // Even-indexed rows (0, 2, 4...)
$("tr:odd")            // Odd-indexed rows (1, 3, 5...)
$("li:eq(3)")          // 4th list item (index 3, zero-based)
$("li:gt(2)")          // List items with index greater than 2
$("li:lt(3)")          // List items with index less than 3
$("li:not(.active)")   // List items without class "active"

Example: Zebra-Stripe a Table

$(function() {
  $("tr:odd").css("background-color", "#f0f0f0");
});

Content Filters

$("p:contains('jQuery')")      // Paragraphs containing "jQuery"
$("td:empty")                  // Table cells with no content
$("div:has(p)")                // Divs that contain a <p> element

Example: Highlight Matching Rows

<table id="employeeTable">
  <tr><td>Alice</td><td>Marketing</td></tr>
  <tr><td>Bob</td><td>Engineering</td></tr>
  <tr><td>Carol</td><td>Marketing</td></tr>
</table>

<script>
$(function() {
  $("tr:contains('Marketing')").css("background-color", "#e8f4fd");
});
</script>

Child Filters

$("li:first-child")       // First <li> in each parent
$("li:last-child")        // Last <li> in each parent
$("li:nth-child(2)")      // Second <li> in each parent (1-indexed)
$("li:nth-child(odd)")    // Every odd child <li>

Difference: :first vs :first-child

  • :first — The first element in the entire matched set on the page
  • :first-child — Every element that is the first child of its own parent
$("li:first")         // Only the very first <li> on the whole page
$("li:first-child")   // First <li> inside EACH <ul>

Visibility Filters

$("div:visible")    // Divs that are currently visible
$("div:hidden")     // Divs that are currently hidden

Example: Show All Hidden Paragraphs

$("#revealBtn").click(function() {
  $("p:hidden").show("fast");
});

Form Filters

$(":text")       // All text input fields
$(":checkbox")   // Checkboxes
$(":radio")      // Radio buttons
$(":submit")     // Submit buttons
$(":selected")   // Selected option in a dropdown
$(":checked")    // Checked checkboxes or radio buttons
$(":disabled")   // Disabled form elements

Example: Gather All Checked Checkboxes

<input type="checkbox" class="interest" value="Music"> Music
<input type="checkbox" class="interest" value="Sports"> Sports
<input type="checkbox" class="interest" value="Travel"> Travel
<button id="getChoices">Show Choices</button>

<script>
$(function() {
  $("#getChoices").click(function() {
    var selected = [];
    $(".interest:checked").each(function() {
      selected.push($(this).val());
    });
    alert("Selected: " + selected.join(", "));
  });
});
</script>

The each() Method

The each() method iterates over each element in a matched set and runs a function for every element.

$("li").each(function(index, element) {
  console.log(index + ": " + $(element).text());
});

Key Points

  • Filters narrow down a jQuery selection to specific elements.
  • Basic filters (:first, :last, :eq, :even, :odd) target elements by index.
  • Content filters target elements by what they contain.
  • Child filters work relative to each element's parent.
  • Form filters are specialized selectors for input elements.
  • each() loops over every matched element to apply logic individually.

Leave a Comment

Your email address will not be published. Required fields are marked *