Is it possible to use JavaScript to change the background color of a row based on the value in a specific column? For example, if the value in the mgr
column is 100
, the row should be green, otherwise it should be blue.
Yes, it is possible to use JavaScript to change the background color of a row based on the value in a specific column. Here’s an example code snippet that should work:
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>mgr</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>100</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>50</td>
</tr>
<tr>
<td>3</td>
<td>Bob</td>
<td>75</td>
</tr>
</tbody>
</table>
<script>
const rows = document.querySelectorAll('tbody tr');
rows.forEach(row => {
const mgr = row.querySelector('td:nth-child(3)').textContent;
if (mgr === '100') {
row.style.backgroundColor = 'green';
} else {
row.style.backgroundColor = 'blue';
}
});
</script>
In this example, we have a table with three columns: id
, name
, and mgr
. We use document.querySelectorAll
to select all the tr
elements in the tbody
, and then loop through them using forEach
. For each row, we use querySelector
to select the td
element containing the mgr
value (which is the third column in our example), and then check if it’s equal to 100
. If it is, we set the backgroundColor
property of the row to 'green'
, otherwise we set it to 'blue'
.