Creative Jar Blog RSS Feed

JavaScript nextSibling and Cross Browser Compatibility

November 7, 2008 16:44 by Alexey

We came across the following Cross Browser JavaScript problem whilst writing a bespoke show/hide function for some client FAQs.

The problem was that we were referencing the 'nextSibling' of an element in our JS using the onClick event. In IE this worked great, however in Firefox the 'nextSibling' could be a line break.

Example:

 <div id=”el1”><img src="imageName.gif" onClick="getNextSibling();" /></div>
 <div id=”el2”>Some text</div>

If the function getNextSibling equates to:  var element2 = document.getElementById(“el1”).nextSibling;
 
In the above, clicking on the image would return the nextSibling as "el2" in IE but "\n" in Firefox.

Breaking down the second line of HTML above as JavaScript would see it, it would look something like this:

"\n " (line break)
with element2.nodeName = “#text”;
element2.nodeType = 3; (that’s TEXT_NODE)
and element2.nodeValue = “\n”; (that’s a line break)


So after a bit of research we found that, if we test for 'nodeType' , and ensure that the nodeType is not equal to 1, then the nextSibling is the element we are after.

var element2 = document.getElementById(“el1”).nextSibling;
while (element2.nodeType !=1)
{
          element2 = element2.nextSibling;
}

And just to make sure...

alert(element2.nodeType);


Job done!


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 05:36

Calendar

January 2009
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567