Michel James
Michel James

Reputation: 75

How to change color of text based on text-value by using css?

I have table data which shows football team statistics.

There is column which have letters like:

  1. "W" (win)
  2. "L" (lose)
  3. "D" (draw)

That's letters are rendered as a separate column, thing is that value is dynamically, and I need to apply different colors:

  1. In case with "W" that text should be green
  2. In case with "L" color red
  3. In case with "D" color grey

Is there are way to do that trough CSS?

.table td:nth-child(3) {
  if letter is === W apply green color?
}

<td>
  "W"
</td>     
<td>
  "L"
</td>  
<td>
  "D"
</td> 

enter image description here

Upvotes: 1

Views: 9478

Answers (3)

subashMahapatra
subashMahapatra

Reputation: 6857

If you can add an attribute, you can target the attribute in CSS for different style rules. Example

 <td data-result-val="W">W</td>
 <td data-result-val="L">L</td>
 <td data-result-val="D">D</td>

in css

 td[data-result-val="L"] { color: red;}
 td[data-result-val="W"] { color: green;}
 td[data-result-val="D"] { color: grey;}

Upvotes: 2

SaboSuke
SaboSuke

Reputation: 792

if you can pass those letters as an attribute to the td element you can do it in CSS like this:

 <td color_code='Your letter'>Your letter</td>

here 'your letter' is the letter that's generated dynamically. Now, simply in CSS, just specify that attribute when calling the td element:

td[color_code='L']{ color: red}

and the same for the rest of the letters.

Upvotes: 2

Marc
Marc

Reputation: 1896

It's not possible any more. The contains pseudo class can do this, but this is deprecated and will not work any more.

What you can do:

Best solution:

When rendering the page, you can render a class at the td: < td class="color-W">W> < /td>.

Not so good:

Or you can set the classes after rendering with javascript or jQuery.

JQuery:

$('td:contains("W")').addClass('color-W');

P.S.: the jQuery :contains pseudo class selector is parsed by jQuery and works fine.

Upvotes: 1

Related Questions