Zebra striping tables in jQuery with minimal code.
This is some really simple code to add zebra stripes to your HTML tables, this is really good for tables with long rows to ease readability, and can be tedious to add by hand.
Example zebra stripes in jQuery
$(document).ready(function(){
$(".zebratable").each(function(){
var $s=0;
$(this).find("tr").each(function(){
var $t = $(this).children("td");
$s++;
if($s%2==1)
$t.addClass("stripe");
else
$t.removeClass("stripe");
});
});
});
When the document is ready, the code finds all tables with the class ‘zebratable’, you add this class to every table you want stripes. It then runs through finding all table rows. For each of the rows that has TD tags it adds the class ‘stripe’, but only on every other row (this is the $s%2 part of the if statement. This code completely ignores any TH (table header) tags so you can style those seperately.
Your table should look something like below. Though you can style it however you want, as long as you have the class ‘zebratable’ in there.
| Table header | Something |
|---|---|
| Line #1 | xxxxx |
| Line #2 | xxxxx |
| Line #3 | xxxxx |
| Line #4 | xxxxx |
| Line #5 | xxxxx |
| Line #6 | xxxxx |
| Line #7 | xxxxx |
| Line #8 | xxxxx |
| Line #9 | xxxxx |
On my particular example, the CSS looks like this for the table.
th{
text-align: left;
background-color: #6CC;
}
.stripe{
background-color: #eee;
}
Alternate method:
$(document).ready(function() {
$(‘.zebratable’).each(function() {
$(this).find(‘tr:not(:has(th)):odd’).addClass(‘odd’);
$(this).find(‘tr:not(:has(th)):even’).addClass(‘even’);
});
});