Write jQuery code to add alternate row colors to a table

Description: Give the class even to the rows at position 2, 4, … and the class odd to the others.

Hint:

  • :nth-child() in the selector, or the index of each().

HTML of the page

<table id="t">
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
  <tr><td>Row 4</td></tr>
</table>

Solution

$('#t tr:nth-child(even)').addClass('even');
$('#t tr:nth-child(odd)').addClass('odd');
HTML after the code runs

<table id="t">
<tbody>
<tr class="odd">
<td>Row 1</td>
</tr>
<tr class="even">
<td>Row 2</td>
</tr>
<tr class="odd">
<td>Row 3</td>
</tr>
<tr class="even">
<td>Row 4</td>
</tr>
</tbody>
</table>

How it works

  • :nth-child(even) is a CSS selector, so it is fast and standard.
  • The classes are used by CSS for the colors.

Read jQuery Selectors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.