jQuery Selector for Odd Table Rows

This guide provides a direct solution for selecting all odd table rows using jQuery. You will learn the exact selector syntax, understand how jQuery's zero-based indexing affects row selection, and see alternative CSS-based selectors that provide consistent visual results when styling tables.

The primary jQuery selector for targeting odd table rows is $("tr:odd").

$("tr:odd").css("background-color", "#f2f2f2");

Understanding Zero-Based Indexing

When using the :odd pseudo-class selector, jQuery uses zero-based indexing:

  • Index 0 (1st row) is considered even.
  • Index 1 (2nd row) is considered odd.
  • Index 2 (3rd row) is considered even.
  • Index 3 (4th row) is considered odd.

Because counting begins at index 0, $("tr:odd") selects the 2nd, 4th, and 6th rows visually. If your goal is to select visually odd rows (the 1st, 3rd, and 5th rows), you must use the :even selector instead:

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

Using the standard :nth-child() Selector

If you prefer standard 1-based CSS logic where the 1st row is odd and the 2nd is even, use the :nth-child(odd) selector via jQuery:

$("tr:nth-child(odd)").css("background-color", "#f2f2f2");

Scoping to Table Bodies

To prevent your selector from targeting rows inside table headers (<thead>), scope the selector specifically to the table body (<tbody>):

$("#myTable tbody tr:odd").addClass("highlight");