jQuery Selector Filters

jQuery Selector Filters

jQuery provides several powerful pseudo-class filters that allow you to refine your HTML selections.

These filters are attached directly to standard CSS selectors using a colon (:).

They are incredibly useful for styling tables, lists, and dynamically generated content.


The :first and :last Filters

The :first filter specifically selects the very first occurrence of an element.

The :last filter specifically selects the very last occurrence of an element.

First and Last Example:

$(document).ready(function(){
  // Highlights only the first paragraph on the page
  $("p:first").css("background-color", "yellow");
  

// Highlights only the last paragraph on the page $("p:last").css("background-color", "lightblue"); });


The :even and :odd Filters

The :even and :odd filters are heavily used for styling striped data tables.

The :even filter selects elements with an even index number (0, 2, 4, etc.).

The :odd filter selects elements with an odd index number (1, 3, 5, etc.).

Remember that in programming, index numbers start strictly at 0!

Even and Odd Example:

$(document).ready(function(){
  // Stripes the table rows for better readability
  $("tr:even").css("background-color", "#eee");
  $("tr:odd").css("background-color", "#fff");
});

Positional Filters: :eq, :gt, and :lt

These three filters allow you to select elements based strictly on their exact index position.

Greater Than Example:

$(document).ready(function(){
  // Selects all list items with an index greater than 1
  $("li:gt(1)").css("color", "red");
});

Exercise 1 of 1

?

When using the :even and :odd filters, what index number does the very first element in the DOM have?