I would like to add a class to all of one of my elements siblings. I manage to do this on all except for the first one of the elements which I clicked on.
I would like to get all of my siblings. Could someone please enlighten me?
Thank you
See HTML & JS below:
<table>
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
<th>four</th>
</tr>
</thead>
<tr id="first">
<td>row11</td>
<td>row12</td>
<td>row13</td>
<td>row14</td>
</tr>
<tr>
<td>row21</td>
<td>row22</td>
<td>row23</td>
<td>row24</td>
</tr>
<tr>
<td>row31</td>
<td>row32</td>
<td>row33</td>
<td>row34</td>
</tr>
<tr>
<td>row41</td>
<td>row42</td>
<td>row43</td>
<td>row44</td>
</tr>
</table>
document.querySelectorAll("#first").forEach(element => {
let childs = element.children;
for (allChildren of childs) {
allChildren.addEventListener("click", function() {
let current = allChildren.parentElement;
let nextSibling = current.nextSibling.nextElementSibling;
while(nextSibling) {
nextSibling = nextSibling.nextElementSibling;
console.log(nextSibling);
nextSibling.classList.add("added_test")
}
})
}
});
It seems you are getting the next sibling twice. Put the 2nd next sibling line last in your while loop.