I was recently working on a project where there were tables edited in a database so I had no control over the colours of the various cells (and didn’t want to have to do the striping manually). I eventually found the following code and altered it to suit my needs:
if(window.addEventListener){
window.addEventListener('load', stripe, false);
}else{
window.attachEvent('onload', function(){ stripe(); });
}
function stripe() {
var evenColor = "#eee";
var oddColor = "#fff";
var tables = document.body.getElementsByTagName('table');
for(i=0;i<tables.length;i++){
if(tables[i].className == 'press'){
var even = false;
var tbodies = tables[i].getElementsByTagName("tbody");
for (var j = 0; j < tbodies.length; j++) {
var trs = tbodies[j].getElementsByTagName("tr");
for (var k = 0; k < trs.length; k++) {
var tds = trs[k].getElementsByTagName("td");
for (var l = 0; l < tds.length; l++) {
var mytd = tds[l];
mytd.style.backgroundColor = even ? evenColor : oddColor;
}
even = ! even;
}
}
}
}
}
The first part of this code causes the function to run automatically when the page finishes loading.
The function loops over all table tags, then finds the ones with a class of ‘press’ (this table held a list of press releases), then loops over all the tbody tags, then the tr tags, then all the td tags. When we reach the td we just add the backgroundColor style for the colour we are currently using.
You just need the following script in your <head> and make sure your tables have the correct class and are properly coded;
<script type="text/javascript" src="stripe.js"></script>
<table class="press" cellspacing="0">
<thead>
<tr>
<th scope="col">Released on</th>
<th scope="col">Title</th>
</tr>
</thead>
<tbody>
<tr>
<td class="date">[date]</td>
<td>[title]</td>
</tr>
<tr>
<td class="date">[date]</td>
<td>[title]</td>
</tr>
<tr>
<td class="date">[date]</td>
<td>[title]</td>
</tr>
<tr>
<td class="date">[date]</td>
<td>[title]</td>
</tr>
</tbody>
</table>
And there it is!