Reputation: 356
I want to be able to select all siblings past a certain element, like this:
<ul>
<li>Unselected</li>
<li>Unselected</li>
<li id="start">Start Here</li>
<li>Selected</li>
<li>Selected</li>
<li>Selected</li>
</ul>
I cannot plan for the amount of siblings to select or the number at which it will start, so I'm guessing that there will need to be a .length
in there at some point.
Vanilla JS only please :) Thanks!
Upvotes: 3
Views: 3345
Reputation: 382474
To iterate over the siblings, just use nextElementSibling
:
var e = document.getElementById("start");
while (e = e.nextElementSibling) e.classList.add("selected");
var e = document.getElementById("start");
while (e = e.nextElementSibling) e.classList.add("selected");
.selected {
color: red;
}
<ul>
<li>Unselected</li>
<li>Unselected</li>
<li id="start">Start Here</li>
<li>Selected</li>
<li>Selected</li>
<li>Selected</li>
</ul>
Upvotes: 2
Reputation: 19007
var node = document.getElementById("start")
var sibling = node.nextElementSibling;
This will return the sibling immediately after the node, or null no more siblings are available.
Upvotes: 0
Reputation: 67217
You can select those elements by using ~
selector,
var elems = document.querySelectorAll("#start ~ li");
Upvotes: 7