For some performance reasons, I am trying to find a way to select only sibling nodes of the selected node.
For example,
JavaScript
x
7
1
<div id="outer">
2
<div id="inner1"></div>
3
<div id="inner2"></div>
4
<div id="inner3"></div>
5
<div id="inner4"></div>
6
</div>
7
If I selected inner1 node, is there a way for me to access its siblings, inner2-4
nodes?
Advertisement
Answer
Well… sure… just access the parent and then the children.
JavaScript
1
2
1
node.parentNode.childNodes[]
2
or… using jQuery:
JavaScript
1
2
1
$('#innerId').siblings()
2
Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:
JavaScript
1
12
12
1
function getChildren(n, skipMe){
2
var r = [];
3
for ( ; n; n = n.nextSibling )
4
if ( n.nodeType == 1 && n != skipMe)
5
r.push( n );
6
return r;
7
};
8
9
function getSiblings(n) {
10
return getChildren(n.parentNode.firstChild, n);
11
}
12