I have a table with text in left-most column and numbers in all other columns. How can I color the cells based on the number in them? I want to set the background-color = "red" for negative number and ignore the column with text in it and also ignore the cells with positive numbers in them.
Below is a code that I picked up from another question and modified a little bit but it does not seem to work.
var allTableCells = document.getElementsByTagName("td");
for(var i = 0, max = allTableCells.length; i < max; i++) {
var node = allTableCells[i];
var currentVal = node.childNodes[0].nodeValue;
if(currentVal.toFixed){
if (currentVal <0)
node.style.backgroundColor = "red"; // -ive number
} else{
// do nothing, the cell has text
}
}
You should parse the number:
var allTableCells = document.getElementsByTagName("td");
for(var i = 0, max = allTableCells.length; i < max; i++) {
var node = allTableCells[i];
var currentVal = parseFloat(node.childNodes[0].nodeValue);
if(currentVal!=NaN){
if (currentVal <0)
node.style.backgroundColor = "red";
}
}
Or better with jQuery & css:
Script:
$("td").filter(function(c){
var num=parseFloat(this.innerText);
return num!=NaN && num < 0;
}).addClass("neg");
or
$("td:contains('-')").addClass("neg");
CSS:
.neg{
background-color: red;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.