Hi,
Here’s a codepen example
I’ve got a table and have different columns with different colours for each.
Within each column I would like to have the <td>s odd and even to be different colours e.g, a green column, with two light shades of green. A blue column with two lighter shades of blue for the cells and so forth.
I thought I could achieve this by indexing the colgroup and then adding a class, using jquery, to each <td> with an .eq() within a row but it seems that table cells are indexed from the entire table, not each row.
Does that make sense? Can anyone offer a suggestion?
Thanks
Hi,
You would have to iterate over the table rows, then iterate over the cells it contains and apply the class names accordingly.
<table>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</table>
table {
width:100%;
border-collapse:collapse;
}
td {
padding:7px;
border:#4e95f4 1px solid;
}
.col0Odd {
background-color: #0000FF;
}
.col0Even {
background-color: #0066FF;
}
.col1Odd {
background-color: #32cd32;
}
.col1Even {
background-color: #00FF66;
}
.col2Odd {
background-color: #808080;
}
.col2Even {
background-color: #C0C0C0;
}
$("tr").each(function () {
var oddEven = ($(this).index() % 2 === 0) ? "Even" : "Odd";
$(this).find("td").each(function () {
var colNo = $(this).index();
$(this).addClass("col" + colNo + oddEven);
});
});
Here’s a demo