Select Numbers in an HTML table by table data

Asked

Viewed 68 times

-1

I have a table with several "td"(table data) and would like to adapt a Javascript code that selects these values from within the "td" and make comparisons so that, for example, when the value inside the "td" is above 5 the number is in red.

But it is a table with both numeric and string. example:

    <tbody id ="tbl">
    <tr>  
        <td>açaí</td>
        <td>2</td>
     </tr>     
      <tr>  
        <td>Coco</td>
        <td>6</td>
     </tr>

When making an IF to compare the number on with 5 or > , I can’t get the value. Am I referencing the tag wrong? would like to know if there is another solution since I use a table with TASTE and QUANTITY (strg and int)

  • 1

    Hello Ruan. Ask the question the code you tried to do.

1 answer

1


If your table always follows this rule of having two tds for tr within the tbody, you can filter only this second td which has the numerical data.

Here’s an example of how to do this, using the querySelectorAll, that will return all the elements according to the given filter:

const tabela = document.querySelectorAll("tbody > tr > td:nth-child(2)");

for(const dados of tabela) {
    if(dados.innerText > 5){
      dados.classList.add("vermelho");
    //Nesse exemplo, não é necessário o remove, mas fica de exemplo caso precise em sua implementação
    } else {
      dados.classList.remove("vermelho");
    }
}
.vermelho {
  color: red;
}
<table>
    <tbody id ="tbl">
        <tr>  
            <td>açaí</td>
            <td>2</td>
        </tr>     
        <tr>  
            <td>Coco</td>
            <td>6</td>
        </tr>
    </tbody>
</table>


If you don’t want to work with css classes, you can directly edit the style of the element by the property style:

const tabela = document.querySelectorAll("tbody > tr > td:nth-child(2)");

for(const dados of tabela) {
    if(dados.innerText > 5){
      dados.style.color = "red";
    }
}
<table>
    <tbody id ="tbl">
        <tr>  
            <td>açaí</td>
            <td>2</td>
        </tr>     
        <tr>  
            <td>Coco</td>
            <td>6</td>
        </tr>
    </tbody>
</table>


Documentations:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

  • I think my biggest difficulty was actually selecting the correct "td" because yes, I follow a pattern in the Rows table. Thanks for the answer was very objective

  • good answer but, can add more information than is the selector nth-child?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.