For some performance reasons, I am trying to find a way to select only sibling nodes of the selected node. For example,
<div id="outer">
<div id="inner1"> </div>
<div id="inner2"> </div>
<div id="inner3"> </div>
<div id="inner4"> </div>
</div>
If I selected inner1 node, is there a way for me to access its siblings, inner2-4
nodes?
Here's how you could get previous, next and all siblings (both sides):
This will return the sibling immediately after it, or null no more siblings are available. Likewise, you can use
previousSibling
.[Edit] On second thought, this will not give the next
div
tag, but the whitespace after the node. Better seems to beThere also exists a
previousElementSibling
.From 2017:
straightforward answer:
element.nextElementSibling
for get the right element sibling. also you haveelement.previousElementSibling
for previous onefrom here is pretty simple to got all next sibiling
Quick:
https://codepen.io/anon/pen/LLoyrP?editors=1011
Get the parent's children as an array, filter out this element.
Edit:
And to filter out text nodes (Thanks pmrotule):