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 filter specifically selects the very first occurrence of an element.
The :last filter specifically selects the very last occurrence of an element.
$(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 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!
$(document).ready(function(){
// Stripes the table rows for better readability
$("tr:even").css("background-color", "#eee");
$("tr:odd").css("background-color", "#fff");
});
These three filters allow you to select elements based strictly on their exact index position.
:eq(n) - Selects the element at index exactly equal to n.:gt(n) - Selects all elements with an index greater than n.:lt(n) - Selects all elements with an index less than n.
$(document).ready(function(){
// Selects all list items with an index greater than 1
$("li:gt(1)").css("color", "red");
});
When using the :even and :odd filters, what index number does the very first element in the DOM have?