This is my html page:
JavaScript
x
19
19
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<title>My Page</title>
5
</head>
6
<body>
7
<table>
8
<tr>
9
<td>Apples</td>
10
<td>4</td>
11
</tr>
12
<tr>
13
<td>Bananas</td>
14
<td>13</td>
15
</tr>
16
</table>
17
</body>
18
</html>
19
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
1
2
1
document.querySelectorAll("tbody td:nth-child(2)")
2
.forEach(td=>td.className=+td.textContent>10?"red":"green")
JavaScript
1
2
1
.red {background-color:red}
2
.green {background-color:green}
JavaScript
1
5
1
<table>
2
<tr><td>Apples</td><td><b>4</b></td></tr>
3
<tr><td>Bananas</td><td>13</td></tr>
4
<tr><td>Oranges</td><td><em>17</em></td></tr>
5
</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.