-1

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")
            }
        })
    }
});

The console output when I click on the first row. enter image description here

Dan
  • 111
  • 1
  • 13

2 Answers2

1

It seems you are getting the next sibling twice. Put the 2nd next sibling line last in your while loop.

Dale
  • 1,613
  • 4
  • 22
  • 42
  • I moved: nextSibling.classList.add("added_test") to the top of the while loop. Thanks for your hint, it made think out of the box again. – Dan Jan 14 '21 at 19:20
0

Can you send the code written on click event? for better understanding the problem

Tej
  • 13
  • 4