Reputation: 373
I am unable to change the background color of a table row with jquery.
It works with font color but for some reason not with the background color.
this works:
$(this).parent('tr').css('color', 'red');
but this does not:
$(this).parent('tr').css('background-color', 'green');
Any idea what I am doing wrong? I couldn't find a similar case on the internet.
$(document).on('click', "td", function(event) {
$(this).parent('tr').css('color', 'red');
$(this).parent('tr').css('background-color', 'green');
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 500px;
margin: 50px 0 0 50px;
}
td,
th {
border: 1px solid #cacaca;
text-align: left;
padding: 8px;
background-color: #f5f5f5;
}
th {
background-color: #dce0e3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus </td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari </td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>
Upvotes: 0
Views: 2357
Reputation: 2488
As you have given td background color #f5f5f5
that's why it's not happening. In jquery you are applying it to tr.
$(document).on('click', "td", function(event) {
$(this).parent('tr').css('color', 'red');
$(this).parent('tr').css('background-color', 'green');
$(this).parent('tr').find('td').css('background-color', 'green');
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 500px;
margin: 50px 0 0 50px;
}
td,
th {
border: 1px solid #cacaca;
text-align: left;
padding: 8px;
background-color: #f5f5f5;
}
th {
background-color: #dce0e3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus </td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari </td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>
Upvotes: 2
Reputation: 4560
Your code is correct, but you can't see background code assigned to tr
because you have td {background-color: #f5f5f5;}
style that paints over your tr
.
Upvotes: 3