Reputation: 51
i have this function to detect when i click on a table row. I want it to turn the clicked on row a certain colour and remove the active class from all other rows. Currently it just makes every row i click on red without removing the colour from the other rows.
html:
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr")[0];
tbody.onclick = function (e) {
e = e || window.event;
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
tbodyRows.classList.remove('active');
target.classList.add('active');
}
js:
<table id="data">
<thead>
<tr>
<th class="number" style="text-align:center">#</th>
<th class="time" style="text-align:center">time</th>
<th class="artist">artist</th>
<th class="song">song</th>
</tr>
</thead>
<tbody id="song-data"></tbody>
</table>
Upvotes: 1
Views: 1162
Reputation: 51
You aren't possible to remove all the color from the other rows, because you are not deleting the other rows classes, you are only deleting one, I think a better way to show you is doing it, so I did this (I also think you can refactor a little more):
const table = document.getElementById('data');
let tableBody = table.querySelector('tbody');
tableBody.onclick = function (e) {
let tableRows = table.querySelectorAll('tbody tr');
let target = e.target.parentNode;
while (target.nodeName !== 'TR') {
target = target.parentNode;
}
tableRows.forEach((element) => {
element.classList.remove('active');
});
target.classList.add('active');
}
.active {
background-color: red;
}
<table id="data">
<thead>
<tr>
<th class="number" style="text-align:center">#</th>
<th class="time" style="text-align:center">time</th>
<th class="artist">artist</th>
<th class="song">song</th>
</tr>
</thead>
<tbody id="song-data">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 187
This should work. Notice how tBodyRows now references all table rows (removed the [0]
) and how we iterate over it with forEach()
.
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr");
tbody.onclick = function (e) {
e = e || window.event;
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
Array.from(tbodyRows).forEach(elem => {
elem.classList.remove('active')
})
target.classList.add('active');
}
Upvotes: 0