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 >
<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>
CodePudding user response:
Just target table element with class selector .info
then find all td
that are first-child
, then filter them by text content (note: even if in your HTML is space, textContent returns empty string). Finaly set background color with jQuery.css
. Alternatively you can define CSS
rule and use jQuery.addClass
.
$(document).ready(colorMissingPayment);
function colorMissingPayment() {
$(".info").find("td:first-child").filter( (i,o) => o.innerText === "")
.css("background-color", "red");
};
<script
src="https://code.jquery.com/jquery-3.6.3.min.js" crossorigin="anonymous"></script>
<table >
<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>
CodePudding user response:
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:
$(document).ready(colorMissingPayment);
function colorMissingPayment() {
$(".info td").each(function () {
const value = $(this).text();
if (value.trim() === '') {
$(this).addClass('is-empty')
};
});
};
.info table tr:has(td.is-empty) td:first-child {
background-color: red;
}
CodePudding user response:
You are targeting the wrong element.
$(".info td").each(function () {
var value = $(this).text();
}
$(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:
<tr>
<th id="ID_amount">Amount</th>
<th style="width:500px">Notes</th>
</tr>
$(".info #ID_column").each(function () {
var value = $(this).text();
});
CodePudding user response:
.info tr>td:nth-child(1):empty {
background-color: red;
}
<table >
<tr>
<td>
<table>
<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>
You can achive this by just using css. Note space inside the "td" is removed.