How do I make a table cell’s background change according to the data it stores?



This is my html page:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>My Page</title>
   </head>
   <body>
      <table>
         <tr>
            <td>Apples</td>
            <td>4</td>
         </tr>
         <tr>
            <td>Bananas</td>
            <td>13</td>
         </tr>
      </table>
   </body>
</html>

I would like to make it so if the quantity of the item is <10, the cell becomes green, while when it is >10, the cell becomes red. I can’t figure how to make it work with one general function, insted of making one specifically for each cell.

Answer

You don’t really need the class assignment. Here is a one-line version using the classes “red” and “green” for the color-definitions:

document.querySelectorAll("tbody td:nth-child(2)")
.forEach(td=>td.className=+td.textContent>10?"red":"green")
.red   {background-color:red}
.green {background-color:green}
<table>
 <tr><td>Apples</td><td><b>4</b></td></tr>
 <tr><td>Bananas</td><td>13</td></tr>
 <tr><td>Oranges</td><td><em>17</em></td></tr>
</table>

The advantage of using .textContent over .innerHTML is that the code will still work in case there is some markup within the <td> elements.



Source: stackoverflow