Alternate Row Color Using jQuery

In this post, you will learn how to create alternate row colors in an HTML table with help of jQuery, Since the table has tr which are representing rows, so we need to change the background-color CSS property of tr in the 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 colors. 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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


Step 2: Create a sample table in the page.

<table>
	<tbody>
		<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>
	</tbody>
</table>

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

<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.

Leave a Reply

Your email address will not be published.