Change the background cell of the table depending on the value

My site is reading an XML file containing information (values) for a data table. I use CSS to create the table and everything works fine.

To get a better user experience, I wondered if it is possible to dynamically change the background color of each cell depending on its value.

For instance:

Each cell containing a number less than "5" has a red background color;

each cell> = "5" has a green background color.

My first solution on this is to use Javascript, but I want to know if there is a way to solve this only with CSS styles?

+5
source share
4 answers

CSS ( JavaScript , CSS). JavaScript, :

var table = document.getElementById('tableID');
var tbody = table.getElementsByTagName('tbody')[0];
var cells = tbody.getElementsByTagName('td');

for (var i=0, len=cells.length; i<len; i++){
    if (parseInt(cells[i].innerHTML,10) > 5){
        cells[i].style.backgroundColor = 'red';
    }
    else if (parseInt(cells[i].innerHTML,10) < -5){
        cells[i].style.backgroundColor = 'green';
    }
}

JS Fiddle demo.

, CSS:

var table = document.getElementById('tableID');
var tbody = table.getElementsByTagName('tbody')[0];
var cells = tbody.getElementsByTagName('td');

for (var i=0, len=cells.length; i<len; i++){
    if (parseInt(cells[i].innerHTML,10) > 5){
        cells[i].className = 'red';
    }
    else if (parseInt(cells[i].innerHTML,10) < -5){
        cells[i].className = 'green';
    }
}

JS Fiddle demo.

:

+9

css. jquery

$('#mytable tr td').each(function(){
  if($(this).text() > 5)$(this).css('background-color','red');
});
+5

, CSS, , IIRC Internet Explorer. .

JavaScript - .

+2
source

without a loop you can do it this way

var val = "ff";

$ ("# grid td: contains ('" + val + "')"). css ('background-color', 'red');

+1
source

All Articles