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.

comments - Post a comment

Anonymous

Anonymous

posted 1 years ago

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

Anonymous

posted 1 years ago

great! thanks a lot!

Anonymous

Anonymous

posted 1 years ago

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

David G. Paul

David G. Paul

posted 1 years ago

oops, sorry about that - sorted now.

hq tube

hq tube

posted 3 hours ago

Soon I feel the pressure break and hot seamen races into my mouth. Then I move my moth away and his dick is spraying my neck and chest with seamen, but the water from the shower washes me quickly. hq tube

sextube

sextube

posted 3 hours ago

We walk to his bedroom and he places me carefully onto his bed and then pushes me up so that my head is on his pillows. sextube

Add a comment

Please feel free to leave comments! Anything that looks like spam will be removed, but other than that I won't censor anything you have to say whether it's positive or negative. Everyone has an opinion so express yourself!