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!
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!
Share Improve this question asked Mar 31, 2016 at 18:08 jasonetcojasonetco 3561 gold badge4 silver badges11 bronze badges 1- 2 @RajaprabhuAravindasamy I assume, after the #start – Mark Commented Mar 31, 2016 at 18:10
3 Answers
Reset to default 7You can select those elements by using ~
selector,
var elems = document.querySelectorAll("#start ~ li");
DEMO
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>
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.