Alternating Row Coloration, WordPress
Putzed around for hours trying to figure out how to make rows of tables alternate colors using javascript. Here’s the change to wp-content/themes/default/header.php:
Replace
</head> <body>
with
<script type="text/javascript">
<!--
function altrows(className, firstColor, secondColor) {
var tableElements =
document.getElementsByTagName('table');
var i, j, k;
var table, tbody, rows;
for(i = 0; i < tableElements.length; i++) {
table = tableElements.item(i);
if (table.className != className) continue;
// iterate through <tbody> elements
var tbodyElements =
table.getElementsByTagName('tbody');
for(j = 0; j < tbodyElements.length; j++) {
tbody = tbodyElements.item(j);
rows = tbody.getElementsByTagName('tr');
for(k = 0; k < rows.length; k++) {
if (k % 2)
rows.item(k).style.background =
secondColor;
else
rows.item(k).style.background =
firstColor;
}
}
// iterate through <tr> elements in case <tbody>
// tags omitted in table
rows = table.getElementsByTagName('tr');
for(j = 0; j < rows.length; j++) {
if (j % 2)
rows[j].bgColor = secondColor;
else
rows[j].bgColor = firstColor;
}
}
}
-->
</script>
</head>
<body onload="altrows('striped', '#ffffff', '#eeddff');">
Setting the class attribute of any table element to “striped” will now cause the color of the rows to alternate between firstColor and secondColor. First though, just for some stylin’, I appended to wp-content/themes/default/style.css:
table.striped {
border: solid 1px black;
border-collapse: collapse;
}
table.striped td {
border: dashed 1px black;
padding: 4px;
}
Here is an example table:
| storms | will |
| come | this |
| we | know |
| for | sure |
Here is the same table without the class attribute set to “striped”:
| storms | will |
| come | this |
| we | know |
| for | sure |