Html table sets some cell text colors based on value

I have an html table and in a specific column the text is either set to 'Y' or 'N'. I am wondering if it is possible to set the text color in the Red program code on load if the value is'N '?

<table> <tr> <td>N</td> <td>Y</td> </tr> </table> 
+4
source share
3 answers

Using jQuery , this is easy:

 <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#table_id td.y_n').each(function(){ if ($(this).text() == 'N') { $(this).css('background-color','#f00'); } }); }); </script> </head> <body> <table id="table_id"> <tr><th>Question</th><th>Y/N?</th></tr> <tr><td>I am me.</td><td class="y_n">Y</td></tr> <tr><td>I am him.</td><td class="y_n">N</td></tr> <tr><td>I am not sure.</td><td class="y_n">Y</td></tr> <tr><td>This is a table.</td><td class="y_n">Y</td></tr> </table> </body> </html> 

Note. I tested the above file and it works. Copy it to your desktop, save as yn.html and run it in a browser.

EDIT: execute using a pure selector and not rely on the if statement ...

 $(document).ready(function(){ $("#table_id td.y_n:contains('N')").css('background-color','#fcc'); }); 

This followed Tyler Holien's answer. This would be the best way to do this, since it does not include so many function calls and is more expressive in less code. NOTE. Unfortunately, do not use this version if there is other content that may contain N and should not be selected, since contains will select all the text with N in it, and not just the text "N".

+8
source

Try using the following CSS:

 td[value="N"] { color: red; } 
+3
source

This is what I did

  $('.dataframe td').each(function(){ var num = parseFloat($(this).text()); if (num > 0) { $(this).addClass('success'); //$(this).css('color','Green'); } else if (num < 0) { $(this).addClass('danger'); //$(this).css('color','Red'); } }); 
+1
source

Source: https://habr.com/ru/post/1338165/


All Articles