'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.



Solution 1:[1]

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>

Solution 2:[2]

In the jQuery, do this instead

$(".tableclass tr").click(function(){
    $(this).css("background-color","#AEB6BF")
});

Solution 3:[3]

<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>

**If you want to change the row color on hover or on click, you can do this using css.** 

.tableclass tr:hover, .tableclass tr:active, .tableclass tr:visited{
background-color: #CCD1D1;
cursor:pointer;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Anupam Majhi
Solution 3