ozyy ozyy - 1 year ago 80
CSS Question

Change the background color of a td element depending on his numeric value

I have a table structure where I want to change the background color depending on the value.

For example

<td class="tg-yw42">0</td>
<td class="tg-yw43">1</td>
<td class="tg-yw44">0</td>


So if value is => 0 apply green background otherwise leave it as it is.

Hope this make sense

Answer Source

You can loop through the table rows and apply css based on the criteria of table cell text == 0.

$("table td").map(function () {
  if (parseInt($(this).text()) === 0) $(this).css("background-color", "green")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
	<tr>
		<td class="tg-yw42">0</td>
		<td class="tg-yw43">1</td>
		<td class="tg-yw44">0</td>
	</tr>
</table>

ES6 way:

$("table td").map((i, el) => parseInt($(el).text()) === 0 ? $(el).css("background-color", "green") : "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download