Piero Alberto Piero Alberto - 6 months ago 9
jQuery Question

Set CSS rules depending the value of a table cell

How can I apply How can I apply my CSS rules on a with a certain value inside?

<table>
<tr>
<td>Name</td>
<td>John</td>
<tr>
</table>


For example, how can I set the color:black in the td with the value John? Is it possible only with CSS?how?

Answer

Here is a JS solution, which loops through all instances of td's and checks their contents. It appends a class to td's which have inner content of "John" in my example.

var el = document.getElementsByTagName("td");
for (var i = 0; i < el.length; i++) {
  if(el[i].innerHTML == "John") {
    el[i].className += " " + "test";
  }
}
.test {
  color: red;
}
<table>
  <tr>
    <td>Name</td>
    <td>John</td>
  <tr>
</table>

EDIT - the above is a basic example of course - you can expand and tailor to your needs.

Comments