17 August, 2007

Interleaved table

Every time I hear question: "How to paint odd and even rows in html table in different colors".



Here is the example how to do it simple:

<html>
<head>

<style type="text/css">

.odd {background-color: #eee;}
.even {background-color: #fff;}

</style>

<script type="text/javascript">

function zebra(tableId)
{
var table=document.getElementById(tableId);
if (table)
{
var rows = table.getElementsByTagName("tr");

for (var i = 0; rows.length > i; i++)
{
rows[i].className = ((i % 2) == 0 ? "odd" : "even");
}
}
}

</script>
</head>

<body>

<table id="irregular">
<tr>
<td>break</td>
<td>broke</td>
<td>broken</td>
</tr>
<tr>
<td>buy</td>
<td>bought</td>
<td>bought</td>
</tr>
<tr>
<td>catch</td>
<td>caught</td>
<td>caught</td>
</tr>
<tr>
<td>forget</td>
<td>forgot</td>
<td>forgotten</td>
</tr>
</table>


<script type="text/javascript">
zebra("irregular");
</script>

</body>
</html>

No comments: