jasonetco
jasonetco

Reputation: 356

JavaScript select all siblings past an element

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

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

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

Rajshekar Reddy
Rajshekar Reddy

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You can select those elements by using ~ selector,

var elems = document.querySelectorAll("#start ~ li");

DEMO

Upvotes: 7

Related Questions