SyntaxStudy
Sign Up
jQuery jQuery :first, :last, :even, :odd Filters
jQuery Beginner 4 min read

jQuery :first, :last, :even, :odd Filters

jQuery extends standard CSS with a collection of custom pseudo-class selectors for positional and content-based filtering. These can be used inside $() or as arguments to .filter() for concise, readable element selection.

Positional Pseudo-Selectors

:first and :last select the first and last elements in the matched set respectively. :even and :odd use zero-based indices — :even matches indices 0, 2, 4… and :odd matches 1, 3, 5… This is the opposite of what you might expect from CSS :nth-child(odd).

Content and Form Pseudo-Selectors

jQuery also defines :contains(text), :empty, :parent, :has(selector), and form-specific pseudo-classes like :checked, :selected, :disabled, :enabled, :input, and :text.

  • $('tr:even') — every other table row (0, 2, 4…)
  • $('li:first') — first list item
  • $('li:last') — last list item
  • $('p:contains("jQuery")') — paragraphs with that text
  • $('td:empty') — empty table cells

Note that jQuery custom pseudo-classes like :first, :even, and :contains cannot be reliably used with querySelectorAll (jQuery's fast path), so they may be slightly slower than native CSS equivalents on very large DOMs.

Example
// Stripe a table using :even / :odd
$('#data-table tbody tr:even').css('background', '#f9f9f9');
$('#data-table tbody tr:odd').css('background',  '#fff');

// Style first and last items
$('ul.menu li:first').addClass('menu-home');
$('ul.menu li:last').addClass('menu-end');

// Find paragraphs containing a keyword
$('p:contains("important")').css('border-left', '4px solid red');

// Highlight empty cells
$('td:empty').text('N/A').addClass('empty-cell');

// Count checked checkboxes
var checked = $('input:checked').length;
console.log('Selected items: ' + checked);
Pro Tip

Remember jQuery :even/:odd use zero-based indices — :even matches the 1st, 3rd, 5th rows, not the 2nd, 4th, 6th.