[Django]-HTML – Change color of text depending on value with JS

2👍

You need to get the textContent of the element to test it’s value. And you can use a single class that toggles if it’s positive or not. And either use jquery’s $.addClass() and $.removeClass() or javascript’s classList.add() and classList.remove().

Also as Sujen K. pointed out, you have a tr > div > td for this element, and it should be tr > td > div instead.

var els = document.getElementsByClassName('TransactionAmount');
for (var i = 0; i < els.length; i++) {
  var cell = els[i];
  if (cell.textContent < 0) {
    cell.classList.remove('green')
  } else {
    cell.classList.add('green');
  }
}
.TransactionAmount {
  color: #FF0000;
}

.TransactionAmount.green {
  color: #33FF3C;
}
<table>
  <tr>
    <th>TRANSACTION AMOUNT</th>
    <th>BALANCE AFTER TRANSACTION</th>
    <th>TRANSACTION COMMENT</th>
  </tr>
  <tr>
    <td style="font-family:'Arial',serif;font-size:10pt"><div class="TransactionAmount">-1</div></td>
    <td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.BalanceAfterTransaction }}</td>
    <td style="color:white">{{ Transaction.TransactionComment }}</td>
  </tr>
  <tr>
    <td style="font-family:'Arial',serif;font-size:10pt"><div class="TransactionAmount">0</div></td>
    <td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.BalanceAfterTransaction }}</td>
    <td style="color:white">{{ Transaction.TransactionComment }}</td>
  </tr>
  <tr>
    <td style="font-family:'Arial',serif;font-size:10pt"><div class="TransactionAmount">1</div></td>
    <td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.BalanceAfterTransaction }}</td>
    <td style="color:white">{{ Transaction.TransactionComment }}</td>
  </tr>
</table>

1👍

There are two problems. The HTML hierarchy should be table > tr > td, and you put div > td. The second problem is addClass. This is from the jQuery library, if you want to use plain JS its possible with className. Try this:

<div id="container">
<h1>{{ Transaction.TransactionDateTime }}</h1>
<table>
    <tr>
    <th>TRANSACTION AMOUNT</th>
    <th>BALANCE AFTER TRANSACTION</th>
    <th>TRANSACTION COMMENT</th>    
    </tr><tr>
    <td style="font-family:'Arial',serif;font-size:10pt"><div id="TransactionAmount">{{ Transaction.TransactionAmount }}</div></td>
    <td style="font-family:'Arial',serif;font-size:10pt">{{ Transaction.BalanceAfterTransaction }}</td>
    <td style="color:white">{{ Transaction.TransactionComment }}</td>
    <script>
        var el = document.getElementById('TransactionAmount');
        if(el<0) {
            el.className += "red";
        } else {
            el.className += "green";
        }
    </script>    
    </tr>
</table>
<h2>Feel free to contact me !</h2>
👤Sujen

Leave a comment