views:

1639

answers:

2

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?

+3  A: 

Well... sure... just access the parent and then the children.

 node.parentNode.childNodes[]

or... using jQuery:

$('#innerId').siblings()

Edit: Cletus as always is inspiring. I dug further. This is how jQuery gets siblings essentially:

function getChildren(n, skipMe){
    var r = [];
    var elem = null;
    for ( ; n; n = n.nextSibling ) 
       if ( n.nodeType == 1 && n != skipMe)
          r.push( n );        
    return r;
};

function getSiblings(n) {
    return getChildren(n.parentNode.firstChild, n);
}
altCognito
Note that jquery.siblings() excludes the current node from the result set.
cletus
Which is a very nice feature!
altCognito
Actually the equivalent of node.parentNode.childNodes[] in jquery is really $(node).parent().children() not $(node).siblings(). It can be a nice feature but it can also be annoying. It depends on what you want.
cletus
You'll wanna check for ELEMENT_NODE nodes with node.parentNode.childNodes, cause it will give you white space text nodes too.
seanmonstar
Alright, Alright, I stopped being lazy and dug up the code!
altCognito
A: 
var childNodeArray = document.getElementById('somethingOtherThanid').childNodes;
Thunderboltz
window.document.documentElement.childNodes[1].childNodes[4]picked up from http://www.howtocreate.co.uk/tutorials/javascript/dombasics
Thunderboltz