Alternate Row Color Using jQuery

In this post you will learn how to create alternate row colors in html table with help of jQuery, Since table has tr which are representing rows, so we need to change background-color css property of tr in table.We can also do the same using the CSS as well.

Jquery is a very power full library for web development, we just use add css class method $("tr:even").css of jquery to alternate table row color. We require jquery lib for alternate row color of table.

alternate-row-color-jquery

Below are step to alternate row color

Step 1 : Include JQuery library

Select Code
1
2
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


Step 2 : Create sample table in page.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table border="1" class="table table-bordered">
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>Feb</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>March</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>April</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>May</td>
    <td>$100</td>
  </tr>
</table>

Step 2 : Include below code for alternate color for div as well as row of table.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
<script>
$(document).ready(function()
{
  //for div
  $("div:odd").css("background-color", "#F4F4F8");
  $("div:even").css("background-color", "#EFF1F1");

  //for table row
  $("tr:even").css("background-color", "#F4F4F8");
  $("tr:odd").css("background-color", "#EFF1F1");
});
</script>

Demo & Download Code

Please feel free to send queries to me using below comment section.