Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
Unexpected behavior using JavaScript less than equal and greater than equal on percentage

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.

enter image description here

Your response is greatly appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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>
about 4 years ago · Juan Pablo Isaza Relatório

0

If the decimal separator always remains a period ('.') and a comma always indicates a number has thousands, you could either

  1. Replace commas with the null string before parsing values as floats, or

  2. 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 selector

to 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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda