firstChild and nextSibling differences between Firefox and Explorer

This post describes a weird difference in how Internet Explorer and Firefox handles the Document Object Model (DOM). In my case I got different browser-behaviour when using firstChild and nextSibling in a javascript. The problem is that the Firefox DOM does not ignore line breaks and whitespaces while IE does.

Instead of using firstChild and nextSibling you can use these functions (look below) that searches for the correct element in both major browsers.

Use getNextSibling(element) instead of element.nextSibling.
Use getFirstChild(element) instead of element.firstChild.

function getNextSibling(startBrother)
{
endBrother=startBrother.nextSibling;
while(endBrother.nodeType!=1)
{
endBrother = endBrother.nextSibling;
}
return endBrother;
}

function getFirstChild(elm)
{
if ( !elm.childNodes.length )
{
return;
}
var children = elm.childNodes.length;
for ( var i = 0; i <= children; ++i )
{
if ( elm.childNodes[i].nodeType == 1 )
{
return elm.childNodes[i];
}
}
return;
}

5 Comments

Simon Lindholm  on mars 11th, 2008

Also note that these methods does not work for end-childs, which is indicated by a firstChild/nextSibling with the value null. To be really conformant, getNextSiblings loop also needs to test for endBrother!=null, and getFirstChild needs to return null instead of void (return;) (plus there is a bug in getFirstChild, the loop should test for

JeffCirceo  on mars 17th, 2009

Thanks just what i needed.

Sylvia  on mars 25th, 2009

It’s really helped. Thank you!!

sam  on oktober 22nd, 2009

Thanks buddy… really helpedd

alberto  on oktober 29th, 2009

Thanks, I’m trying to make my web application mozilla and explorer compatible and this helped a lot.

Leave a Comment