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; }

6 reaktioner till “firstChild and nextSibling differences between Firefox and Explorer”

  1. 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

Lämna ett svar

E-postadressen publiceras inte. Obligatoriska fält är märkta *

Denna webbplats använder Akismet för att minska skräppost. Lär dig hur din kommentardata bearbetas.