I am currently working on a project wherein values less than or equal to 30% will be colored red in the table. I have written the code below that will check every cell in the table and verify its value and from there execute the condition and highlight it with red if true but somehow it is not doing what I expect. Can you help me understand why it only highlights 0%.
<script>
var td = document.getElementsByTagName("td");
var i = 0, tds = td.length;
for (i; i < tds; i++) {
if (parseFloat(td[i].innerHTML) >= 0.00 && parseFloat(td[i].innerHTML) <= 0.30) {
td[i].setAttribute("style", "background:red;");
}
}
</script>
I have attached a screenshot to give you a better idea of what is happening. From the example below, it should also color 12.50% and 25.00% red.
Your response is greatly appreciated.
The main issue is what traktor commented: where you put 0.30 instead of 30. However, here's another way you could write that code:
let aryTD = [...document.getElementsByTagName("td")];
const rxCommas = /,/g; // Regular Expression for locating commas
aryTD.forEach((td)=>
{
let content = td.textContent.replace(rxCommas,""); // remove commas
let float = parseFloat(content);
if (float >= 0 && float <= 30)
{
td.style.backgroundColor = "red";
}
});
<table>
<tr><td>1,335.00%</td></tr>
<tr><td>0.00%</td></tr>
<tr><td>0.00%</td></tr>
<tr><td>0.00%</td></tr>
<tr><td>12.50%</td></tr>
<tr><td>25.00%</td></tr>
<tr><td>37.50%</td></tr>
<tr><td>37.50%</td></tr>
<tr><td>37.50%</td></tr>
<tr><td>50.50%</td></tr>
<tr><td>60.00%</td></tr>
</table>
Try This code
var td = document.getElementsByTagName("td");
var i = 0, tds = td.length;
for (i; i < tds; i++) {
if (parseFloat(td[i].innerHTML) >= 0.00 && parseFloat(td[i].innerHTML) <= 30) {
td[i].setAttribute("style", "background:red;");
}
}
</script>
If the decimal separator always remains a period ('.') and a comma always indicates a number has thousands, you could either
Replace commas with the null string before parsing values as floats, or
Let commas indicate a number is greater than 999.
For an example of the second technique without changing the code a lot:
var td = document.getElementsByTagName("td");
var i = 0, tds = td.length;
for (i; i < tds; i++) {
var value = td[i].textContent;
if( value.indexOf(',') < 0) {
value = parseFloat(value);
if( value >= 0 && value <= 30) {
td[i].style.backgroundColor = "red";
}
}
}
To limit the td elements processed to a column in the table you can use
element.querySelectorAll] in combination with:nth-child, :nth-col or :nth-last-child CSS selectorto select specific column cells which are the children of rows in a table
Note nth-col is still experimental.
Here's a quick example to get second column cells:
let columnCells = document.querySelectorAll("table tr td:nth-child(2)");
for( var i=0; i<columnCells.length; ++i) {
console.log( columnCells[i].textContent);
}
<table>
<tr><td>r1c1</td><td>r1c2</td></tr>
<tr><td>r2c1</td><td>r2c2</td></tr>
<tr><td>r2c1</td><td>r3c2</td></tr>
<table>