Search code examples
jquerynode.jsexpresshandlebars.js

How do I check if td:nth-child(3) is greater than or equal to a percentage?


I'm currently writing a web page that pulls in all this data. In this data there are 3 separate tables. In each table, I want to check if in the 3rd td in that TR is greater than or = to a percentage.

How can I check if {{opendiff}} (which is a percentage already) is greater than or equal to 18% ( this percentage can be hard-coded. ). The row should look something like:

goal | actual | % diff

100%  | 43% | 57%

If the diff% is lower than 50% I would like it to use jquery to toggleClass() so I can make the row turn red (I already created the classes for these TR rows, but I don't know how to implement the check to see if greater than etc.) .

<tr>
    <td class="hide-on-large-only">Dialer</td>
    <td>18 %     </td>
    <td>{{opentransfer}}</td>
    <td>{{opendiff}}</td>
    <td class="hide-on-med-and-down"></td>
</tr>

I found my jquery function jQuery toggleClass() Method. I just don't know how to check if the TD is greater than a % to make the jquery toggleClass().


Solution

  • Don't even need jQuery:

    const cells = Array.from(document.querySelectorAll(".opendiff"));
    
    // fill in random values
    for(const cell of cells) {
        cell.innerHTML = (Math.round(Math.random()*1000)/10) + " %";
    }
    
    // I set t to 50 to make it more likely for red values
    const maxPercentage = 50;
    // for each cell, as above
    for(const cell of cells) {
        cell.classList.toggle("red",parseFloat(cell.textContent)<maxPercentage);
    }
    table td {
     background-color: #cceeFF;
    }
    td.red {
      background-color: #FFDDDD;
    }
    <table>
    <tbody>
    <tr>
        <td class="hide-on-large-only">Dialer</td>
        <td>18 %     </td>
        <td>{{opentransfer}}</td>
        <td class="opendiff">{{opendiff}}</td>
    </tr>
    <tr>
        <td class="hide-on-large-only">Dialer</td>
        <td>18 %     </td>
        <td>{{opentransfer}}</td>
        <td class="opendiff">{{opendiff}}</td>
    </tr>
    <tr>
        <td class="hide-on-large-only">Dialer</td>
        <td>18 %     </td>
        <td>{{opentransfer}}</td>
        <td class="opendiff">{{opendiff}}</td>
    </tr>
    <tr>
        <td class="hide-on-large-only">Dialer</td>
        <td>18 %     </td>
        <td>{{opentransfer}}</td>
        <td class="opendiff">{{opendiff}}</td>
    </tr>
    </tbody>
    </table>