Here is a simple JavaScript solution for making alternative rows of your HTML table different colours.
Normally this wouldn’t be an issue if your HTML table is very small, or if it is dynamically generated by the server but otherwise if the content is static then there is just a case of manual labor to take into consideration and this is where JavaScript comes in to make the job easier.
Imagine the following HTML code…
<table id="myTable"> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> </table>
Now also imagine you have the following CSS…
.other { background-color:red; }
From here all you need is the following JavaScript that ties it all together…
// Create a new class so as not to interfere with the global namespace var MYAPP = {}; /** * Augment the MYAPP class so it includes a method * which stripes the TR elements of the provided table element. * * @class MYAPP * @param String / id / the id value of the table element to be striped */ MYAPP.stripeTable = function(id) { // Grab a reference to the table that we can reuse var table = document.getElementById(id); if (table) { var rows = table.getElementsByTagName("tr"), len = rows.length, other = false; for (var i=0; i<len; i++) { if (other) { rows[i].className = "other"; other = false; } else { other = true; } } } } window.onload = function() { MYAPP.stripeTable("myTable"); };