Samuel Sjöberg's weblog

Skip to navigation

Siblings in the DOM-tree

I have been working a lot with list elements lately and thought I would share a fix I just wrote to find the siblings of an element. Siblings that not are text nodes that is.

Both Firefox and Safari return blank TextNodes from the DOM-tree when previousSibling and nextSibling are being used. This is caused by the nice indentations and spacing that are added for readability.

The fix is simple and I think it should be added to, for example Prototype's Element object.

var Sibling = function() {};
Sibling.previous = function(elm) {
   var s = elm.previousSibling;
   while (s && s.nodeType == 3)
      s = s.previousSibling;
   return s;
}
 
Sibling.next = function(elm) {
   var s = elm.nextSibling;
   while (s && s.nodeType == 3)
      s = s.nextSibling;
   return s;	
}

To get the previous sibling of your element elm you do this:

var sibling = Sibling.previous(elm);

And in the same manner, you can get the next sibling:

var sibling = Sibling.next(elm);

If the sibling does not exist, null is returned. This code is only tested in Safari and Firefox OS X (at the moment), but I believe it should work like a charm on Windows and Internet Explorer as well.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 14th September 2005 18:02 CET. Filed under Javascript and DOM.

0 Comments
0 Pingbacks