JQuery find alternative rows in a table using even and odd selector

By using JQuery even selector we can find the even rows and by using odd selector we can find the odd rows.


Syntax:

$("#tableid tr:even").css("background-color", "#ccc");
The above code will find the even rows in table and apply back ground color.

$("#tableid tr:odd").css("background-color", "#f5f5f5");
The above code will find the odd rows in table and apply back ground color.


Note: when we uses $("#tableid tr:even") it will select the header row also (because header row is the first row and its row index is 0), to overcome this we can use .not('thead tr') in addition to the above selector syntax is as follows

Syntax:
$("#tableid tr:even").not('thead tr').css("background-color", "#ccc");

Example:

Source Code:

<html> <head> <title>JQuery find alternative rows in a table using even and odd selector</title> <style type="text/css"> body{font-family:Arial; font-size:14px;} </style> <script src="http://code.jquery.com/jquery-1.7.2.min.js" language="javascript"></script> <script language="javascript"> $(document).ready(function () { $("#tblstudents").css("font-style", "Arial"); $("#tblstudents tr:even").not('thead tr').css("background-color", "#ccc"); $("#tblstudents tr:odd").css("background-color", "#f5f5f5"); $("#tblstudents th").css({"padding": "5px 10px","color": "#fff"}); $("#tblstudents td").css("padding", "5px 10px"); $("#tblstudents tr th").css("background-color", "gray"); }); </script> </head> <body> <table id="tblstudents" cellspacing="0"> <thead> <tr> <th> S. No. </th> <th> Student Name </th> <th> Total Marks </th> <th> Grade </th> </tr> </thead> <tr> <td> 1 </td> <td> Ravi </td> <td> 500 </td> <td> 2 </td> </tr> <tr> <td> 2 </td> <td> Suresh </td> <td> 600 </td> <td> 1 </td> </tr> <tr> <td> 3 </td> <td> Steave </td> <td> 500 </td> <td> 2 </td> </tr> <tr> <td> 4 </td> <td> Kishore </td> <td> 400 </td> <td> 3 </td> </tr> <tr> <td> 5 </td> <td> Vinay </td> <td> 300 </td> <td> 4 </td> </tr> <tr> <td> 6 </td> <td> Sony </td> <td> 500 </td> <td> 2 </td> </tr> <tr> <td> 7 </td> <td> Laxman </td> <td> 600 </td> <td> 1 </td> </tr> <tr> <td> 8 </td> <td> Krishna </td> <td> 400 </td> <td> 3 </td> </tr> </table> </body> </html>