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!
Currently rated 4.3 by 6 people
- Currently 4.333333/5 Stars.
- 1
- 2
- 3
- 4
- 5