I have a table with class .info
, and I want to set the background color of all td
elements, only in column Amount
, where the value is " "
to red.
The part of setting the color is done like this
$(document).ready(colorMissingPayment);
function colorMissingPayment() {
$(".info td").each(function () {
var value = $(this).text();
if (value == " ") {
$(this).css("background-color", "red")
};
});
};
but that targets all td
elements in the table; how do I target a specific column/th
? An example would be
<table class="info">
<tr>
<td>
<table>
<h4 align="center">2021</h4>
<tr>
<th>Amount</th>
<th style="width:500px">Notes</th>
</tr>
<tr>
<td> </td>
<td>Hello</td>
</tr>
<tr>
<td> 200</td>
<td>Monday</td>
</tr>
<tr>
<td>500+500 </td>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
4
Answers
How much legacy support do you want? There is a new browser css selector called
:has
that can help with this.You’ll still need a bit of JavaScript though:
Demo
You are targeting the wrong element.
$(this) should return every
td
element.It is unclear what do you mean by the value of column Amount? I suggest adding id’s to your elements. That way you can target a specific column. for example:
Just target table element with class selector
.info
then find alltd
that arefirst-child
, then filter them by text content (note: even if in your HTML is space, textContent returns empty string). Finaly set background color withjQuery.css
. Alternatively you can defineCSS
rule and usejQuery.addClass
.You can achive this by just using css.
Note space inside the "td" is removed.