最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript select all siblings past an element - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 7

You 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.

发布评论

评论列表(0)

  1. 暂无评论