Javascript Siblings

Javascript code
Jul
29

The DOM, as accessed by JavaScript, has it's differences between browsers. The previousSibling and nextSibling are two prototype functions that suffer from such differences.

The problem is caused by the way Mozilla Firefox sees characters outside of tags. In the following code example Firefox would see there being a Text sibling between the two P tags.

<p id="para1">Some text</p>
<p id="para2">Some more text</p>

This same code will be intrepreted in Internet Explorer as the nextSibling of para1 being para1 (but in firefox it is the whitespace that occurs between). So what we can use reliably between browsers are:

document.getElementById('para1').nextSibling;
document.getElementById('para2').previousSibling;

To right this wrong we need to waste bandwidth by providing our own code for doing this, or we could just not use nextSibling and previousSibling. If you do decide you need to use them, and for it to be reliable across browsers then you could try the following code:

function getPreviousSibling (elem)
{
  elem = document.getElementById(elem);
  while (elem.tagName == 'undefined') {
    elem = elem.previousSibling;
  };

  return elem;
}


function getNextSibling (elem)
{
  elem = document.getElementById(elem);
  while (elem.tagName == 'undefined') {
    elem = elem.nextSibling;
  };

  return elem;
}

And that should solve the woes of siblings in Mozilla.

your comments - Post a comment

Anonymous

fyi. Minor change needed on my end (FF 2.0.0.4) to get it to perform as intended. Thanks for your article on this, has helped a lot (with minor changed worked for me)

function getPreviousSibling(elem){
elem = document.getElementById(elem);
elem = elem.previousSibling;
do {
elem = elem.previoussibling;
} while (elem.tagName == 'undefined');
}

Anonymous commented 7 years ago
Anonymous

great! thanks a lot!

Anonymous commented 7 years ago
Anonymous

any example on using this code?
I can't seem to make it work.... I still get undefined ....hmm..

Anonymous commented 7 years ago
David G. Paul

oops, sorry about that - sorted now.

David G. Paul commented 7 years ago
David Bernad

Hello,

Many thanks for the functions, but they are not working very well.

Any other idea?

David Bernad commented 5 years ago
David G. Paul

@David Bernad, what sort of problems are you having?

David G. Paul commented 5 years ago
David Bernad

I don't know what is the problem, but i solve it changing

elem = document.getElementById(elem);
while (elem.tagName == 'undefined') {
elem = elem.previousSibling;
};

return elem;

by

var tempNode = elem.previousSibling;
while(tempNode.nodeType != 1){
tempNode=tempNode.previousSibling;
}
return tempNode;

Thanks a lot.

David Bernad commented 5 years ago
blog comments powered by Disqus