Skip to content
Advertisement

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

This is my html page:

JavaScript

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.

Advertisement

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:

JavaScript
JavaScript
JavaScript

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

Advertisement