Best practice: JavaScript-free solution
Don't use JavaScript to determine styling on the client-side. It's a bad practice.
Instead, add a "odd
" or "even
" class on the server-side.
For example if you're using PHP to render your table from an array, here is how you would do it:
<?php
$i = 0;
foreach ($rows as $row) {
$odd_even_class = ($i%2 == 0) ? 'even' : 'odd';
echo '<tr class="'.$odd_even_class.'"> ... </tr>';
$i++;
}
?>
And then style the two classes appropriately using CSS, which will work on all browsers:
.table tr.odd {
background-color: #FFFEE8;
}
.table tr.even {
background-color: #FFFFFF;
}
If using JavaScript, at least avoid affecting all browsers
If you decide to go with the JavaScript solution, at least avoid the overload for browsers supporting modern CSS.
Put the JavaScript fix into a conditional statement that will prevent its execution on other browsers than IE:
<!--[if IE]>
<script>
$(document).ready(function(){
$('.table tr:even').addClass('even');
$('.table tr:odd').addClass('odd');
});
</script>
<![endif]-->
And then make sure to cover both IE and modern browsers at once in the CSS:
.table tr:nth-child(odd),
.table tr.odd {
background-color: #FFFEE8;
}
.table tr:nth-child(even),
.table tr.even {
background-color: #FFFFFF;
}