Select All Even Table Rows Using jQuery

This guide demonstrates how to select all even table rows using jQuery. You will learn the syntax for jQuery's built-in :even selector, explore the standard CSS :nth-child(even) alternative, understand the difference between zero-based and one-based indexing, and see practical code examples for styling alternating rows.

Using the jQuery :even Selector

jQuery provides a dedicated :even pseudo-class selector. In jQuery, index counts start at 0, meaning the first row has an index of 0 (even), the second has an index of 1 (odd), the third has an index of 2 (even), and so forth.

To select even rows across a table, use the following syntax:

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

Preventing Issues with Table Headers

If your table includes a <thead> with header rows, targeting all tr elements will include header rows in the index count, which can disrupt alternating row patterns. To target only the data rows, scope your selector inside the <tbody>:

$("tbody tr:even").addClass("even-row");

Using the :nth-child(even) Selector

Alternatively, you can use the standard CSS :nth-child(even) selector through jQuery. Unlike jQuery's :even selector, :nth-child uses 1-based counting according to standard CSS rules. This means the 2nd, 4th, and 6th rows are matched.

$("tbody tr:nth-child(even)").css("background-color", "#e0e0e0");

Which Method Should You Use?

  • Use tbody tr:even if you prefer jQuery's 0-based indexing (selects rows 1, 3, 5, etc., visually).
  • Use tbody tr:nth-child(even) if you prefer standard 1-based CSS matching (selects rows 2, 4, 6, etc., visually) or plan to migrate the styling directly into a pure CSS stylesheet later.