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">
      <title>My Page</title>

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.


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)")
.red   {background-color:red}
.green {background-color:green}

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