How to change colour background based on value

To change  colour background based on value, for example, to change table cell background based on its value, Javascript code is required. For example, the working example below could be added to an HTML page after the table and it will colour LAST column background to blue if the cell has “SELL”, “Sell” or “sell” text in it. The cell must contain exactly the value which is compared to in if statement (“BLUE” in this case) without spaces, etc.!


<script>
  $(document).ready(function() {
    $("table tr td:last-child").each(
      function(){
        if($(this).html() == "SELL"||$(this).html()=="Sell"||$(this).html()=="sell"){
          $(this).css(" background-color","blue");
        }
        else{
          $(this).css(" background-color","green");
        }
      });
    });
</script>

Make sure that you have a correct DOM path to the element which background needs to be changed. In this example it is:

"table tr td:last-child"
  • Done!