I'm trying to do two things in pure Javascript when the user clicks a table:
- return the number of the row (it works)
- change the background of the row
Here my current code:
document.querySelector('#tableEvents').onclick = function(e) {
let index = e.target.parentElement.rowIndex;
let row = e.target.parentElement;
row.classList.add('table-warning');
console.log(index, row.classList.toString());
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<table id="tableEvents">
<thead>
<tr>
<th scope="col">Col 1</th>
<th scope="col">Col 2</th>
<th scope="col">Col 3</th>
</tr>
</thead>
<tbody class="table-group-divider">
<tr>
<td>1</td>
<td>a</td>
<td>1a</td>
</tr>
<tr>
<td>2</td>
<td>b</td>
<td>2b</td>
</tr>
<tr>
<td>3</td>
<td>c</td>
<td>3c</td>
</tr>
<tr>
<td>4</td>
<td>d</td>
<td>4d</td>
</tr>
</tbody>
</table>
As you can see, it returns the correct index but no changes are made to the row.
Reading the docs I understand it should be enough to add the table-warning
class (for example) to the <tr>
tag.
It actually adds the class (the console shows the classList
value) but no color is shown.
The second issue is how to remove the class from the other rows. In jQuery I would do:
$(this).addClass('table-warning').siblings().removeClass('table-warning');
but I don't understand how to convert the siblings()
call in JavaScript.
Do I need to traverse the whole table, removing the class from each row manually?