Somename Somename - 4 years ago 95
HTML Question

How to change the background of a table row?

My HTML code:

<table class="tableclass">
<th>id</th><th>Name</th><th>Value</th>
<tr>
<td>001</td>
<td>Name 001</td>
<td>This is some value for Key 001</td>
</tr>

<tr>
<td>002</td>
<td>Name 002</td>
<td>This is some value for Key 002</td>
</tr>

<tr>
<td>003</td>
<td>Name 003</td>
<td>This is some value for Key 003</td>
</tr>

<tr>
<td>004</td>
<td>Name 004</td>
<td>This is some value for Key 004</td>
</tr>

</table>


I'm able to show alternate colors with CSS:

tr:nth-child(even) {
background-color: #CCD1D1;
}


And My jQuery to highlight clicked table row :

$(".tableclass tr").click(function(){
$(this).addClass("rowHighlight");
});


The class
.rowHighlight{background-color:#AEB6BF;}


With this code Im not able to change the background color of the odd numbered row that has the background from css. I want to be able to change the background of that rows too.

How do I do that ?

Thanks.

Answer Source

Just use .rowHighlight td{background-color:your color;

$(".tableclass tr").click(function(){
    $(this).addClass("rowHighlight");
});
table {
border:0px solid #CCC;
border-collapse:collapse;
}
td {
    border:none;
}
tr:nth-child(even) {
    background-color: #CCD1D1;
}




.rowHighlight td{background-color:red; padding:0px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="tableclass">
<th>id</th><th>Name</th><th>Value</th>
<tr>
    <td>001</td>
    <td>Name 001</td>
    <td>This is some value for Key 001</td>
</tr>

<tr>
    <td>002</td>
    <td>Name 002</td>
    <td>This is some value for Key 002</td>
</tr>

<tr>
    <td>003</td>
    <td>Name 003</td>
    <td>This is some value for Key 003</td>
</tr>

<tr>
    <td>004</td>
    <td>Name 004</td>
    <td>This is some value for Key 004</td>
</tr>

</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download