Skip to content
Advertisement

change text color depend by value

The data in my table changes with the click of a button. I wanted the items to turn red if they were negative and green if they were positive. Can you help me how to do this?

var lastpr = 100

function act1(){
  const tds =document.querySelector("table").querySelectorAll("tr")[Math.floor(Math.random() * 3)+0].querySelectorAll("td");
    

tds.forEach((item) => {
  item.innerHTML = ((Math.floor(Math.random() * 10)-5)/lastpr)*100;
        });
}
<div>
<table class="table1" style="width:100%;font-weight:bold ;font-size:13px;text-align:center; border: 1px solid black;">
        <tr>
             <td>1</td>
             <td>1</td>
             <td>1</td>
             <td>1</td>
        </tr>
        <tr>
             <td>2</td>
             <td>2</td>
             <td>2</td>
             <td>2</td>
        </tr>
        <tr>
             <td>3</td>
             <td>3</td>
             <td>3</td>
             <td>3</td>
        </tr>           
</table>
</div>
<button onclick="act1()">change</button>

Advertisement

Answer

var lastpr = 100

function act1(){
  const tds =document.querySelector("table").querySelectorAll("tr")[Math.floor(Math.random() * 3)+0].querySelectorAll("td");
 
  tds.forEach((item) => {
    const value = ((Math.floor(Math.random() * 10)-5)/lastpr)*100;
    item.innerHTML = value;
    item.style.backgroundColor = value < 0 ? 'red' : 'green'
  });
}
<div>
<table class="table1" style="width:100%;font-weight:bold ;font-size:13px;text-align:center; border: 1px solid black;">
        <tr>
             <td>1</td>
             <td>1</td>
             <td>1</td>
             <td>1</td>
        </tr>
        <tr>
             <td>2</td>
             <td>2</td>
             <td>2</td>
             <td>2</td>
        </tr>
        <tr>
             <td>3</td>
             <td>3</td>
             <td>3</td>
             <td>3</td>
        </tr>           
</table>
</div>
<button onclick="act1()">change</button>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement