Blog Archive

jQuery shade HTML Table with alternating Row Color

This is a very basic requirement when displaying data in tabular form. Shading alternating rows in different color improves demarcation and readability. In this example with the help of jQuery we will take an existing HTML table and very easily style the alternating rows in different colors.


jquery table alternating row color

Source containing the HTML table - index.html

<html>
<head>
<title>jQuery Table - Alternate Row Color</title>

<link
 href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
 rel="stylesheet" type="text/css" />
<script
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
 type="text/javascript">
</script>
<script
 src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
 type="text/javascript">
</script>
<script type="text/javascript" src="app.js"></script>

<style type="text/css">

table {
 border: 1px black solid;
 border-collapse: collapse;
}

th {
 background-color: #8b8b83;
 color: white;
 text-align:left;
 padding-left: 10px;
}

tr {
 background-color: white;
 margin: 1px;
}

.shaded {
 background-color: #eeeee0;
}

td {
 padding-left: 10px;
 text-align:left;
}
</style>
</head>
<body>
 <table id="myTable">
  <tbody>
   <tr>
    <th>Country Code</th>
    <th>Country Name</th>
    <th>Continent</th>
    <th>Region</th>
   </tr>
   <tr>
    <td>ABW</td>
    <td>Aruba</td>
    <td>North America</td>
    <td>Caribbean</td>
   </tr>
   <tr>
    <td>AFG</td>
    <td>Afghanistan</td>
    <td>Asia</td>
    <td>Southern and Central Asia</td>
   </tr>
   <tr>
    <td>AGO</td>
    <td>Angola</td>
    <td>Africa</td>
    <td>Central Africa</td>
   </tr>
   <tr>
    <td>AIA</td>
    <td>Anguilla</td>
    <td>North America</td>
    <td>Caribbean</td>
   </tr>
   <tr>
    <td>ALB</td>
    <td>Albania</td>
    <td>Europe</td>
    <td>Southern Europe</td>
   </tr>
   <tr>
    <td>AND</td>
    <td>Andorra</td>
    <td>Europe</td>
    <td>Southern Europe</td>
   </tr>
   <tr>
    <td>ANT</td>
    <td>Netherlands Antilles</td>
    <td>North America</td>
    <td>Caribbean</td>
   </tr>
   <tr>
    <td>ARE</td>
    <td>United Arab Emirates</td>
    <td>Asia</td>
    <td>Middle East</td>
   </tr>
   <tr>
    <td>ARG</td>
    <td>Argentina</td>
    <td>South America</td>
    <td>South America</td>
   </tr>
   <tr>
    <td>ARM</td>
    <td>Armenia</td>
    <td>Asia</td>
    <td>Middle East</td>
   </tr>
  </tbody>
 </table>
</body>
</html>

jQuery source for the application - app.js

$(document).ready(function() {

 $("table#myTable tr:nth-child(even)").addClass("shaded");
 
});

How does it work?

Basically it finds the Table by it's id and then add the style "shaded" to the even rows. That's it !