jQuery :even and :odd Selectors for Index Parity

Selecting elements based on their index parity in jQuery is achieved using the :even and :odd positional pseudo-class selectors. This article covers how these selectors operate on a zero-based index system, how to implement them in your scripts, and how to apply them to common use cases such as alternating row styles in lists or tables.

Understanding Zero-Based Indexing

jQuery uses a zero-based indexing system for its elements. This means the count begins at 0 rather than 1. Consequently, the index parity behaves as follows:

  • Index 0 (1st DOM element): Considered even
  • Index 1 (2nd DOM element): Considered odd
  • Index 2 (3rd DOM element): Considered even
  • Index 3 (4th DOM element): Considered odd

Because the first visible element has an index of 0, the :even selector targets the 1st, 3rd, 5th, and subsequent odd-numbered visual elements. The :odd selector targets the 2nd, 4th, 6th, and subsequent even-numbered visual elements.

The :even Selector

The :even selector matches all elements that have an even index number within the matched set.

Syntax:

$("selector:even")

Example: To select all even-indexed list items and apply a background color:

$("li:even").css("background-color", "#f2f2f2");

This applies styling to the first, third, fifth, and all subsequent alternating list items.

The :odd Selector

The :odd selector matches all elements that have an odd index number within the matched set.

Syntax:

$("selector:odd")

Example: To select all odd-indexed list items and apply a background color:

$("li:odd").css("background-color", "#ffffff");

This applies styling to the second, fourth, sixth, and all subsequent alternating list items.

Practical Implementation: Zebra-Striped Table

A standard use case for index parity selection is creating zebra-striped table rows for improved readability.

HTML:

<table id="data-table">
  <tr><td>Row 1 (Index 0)</td></tr>
  <tr><td>Row 2 (Index 1)</td></tr>
  <tr><td>Row 3 (Index 2)</td></tr>
  <tr><td>Row 4 (Index 3)</td></tr>
</table>

jQuery:

$(document).ready(function() {
  // Apply gray background to the 1st and 3rd rows
  $("#data-table tr:even").css("background-color", "#e0e0e0");

  // Apply white background to the 2nd and 4th rows
  $("#data-table tr:odd").css("background-color", "#ffffff");
});

Contextual Filtering with .filter()

You can also use .filter() alongside :even and :odd to chain methods or refine existing jQuery collections:

var $rows = $("#data-table tr");

$rows.filter(":even").addClass("row-even");
$rows.filter(":odd").addClass("row-odd");

This approach allows you to cache the main selector query first, improving DOM traversal performance when dealing with large datasets.