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
jQuery Selectors
jQuery Traversing: Ancestors
jQuery Traversing: Descendants
jQuery Traversing: Siblings
jQuery Traversing: Filtering
Exercises & Assignments
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?