There are a few issues that need to be addressed:
document.querySelectorAll
will return a NodeList
, which is a collection of elements when querying for the <td>
tag. In order to handle multiple elements, it is recommended to loop through each element in the NodeList
using .forEach
.
Currently, there is no reference to the .classList
, so calling
classList.add("available-green");
will not produce any results. When utilizing a forEach
loop, the current element (the first parameter of the .forEach
method) can be used to change the classList accordingly.
The variable status
is predefined within the window
object. It is advisable to avoid using such global variables to prevent unexpected behavior.
Although not mandatory, it is generally recommended to use .textContent
instead of .innerHTML
when retrieving text content from an element, especially if HTML is not being manipulated.
Refer to the example below for a practical demonstration:
var tableData = document.querySelectorAll("td");
tableData.forEach(function(element) {
if(element.textContent === "available") {
element.classList.add("available-green");
}
});
.available-green {
color: lightgreen;
}
<table border=1>
<tr>
<td>booked</td>
<td>available</td>
<td>available</td>
<td>booked</td>
</tr>
</table>