childNodes.length discrepancies in IE and Firefox

February 11th, 2006

I wrote a standard loadXML JavaScript function that goes off, opens an XML files, grabs the whole document and returns it.

I put the contents of the document into a variable called root and then did:

alert(root.childNodes.length);

Here's my XML file:

<?xml version="1.0" ?>

<relatedtopics>

	<topic id="createrolegroup" href="createrolegroup.html">Create a role group</topic>
	<topic id="usesettingseditor" href="usesettingseditor.html">Use the Settings editor</topic>
	<topic id="turnonuserfriendlydatesinsearchqueries" href="turnonuserfriendlydatesinsearchqueries.html">Turn on user-friendly dates in search queries</topic>
	<topic id="systempicklistsindetail" href="systempicklistsindetail.html">The system picklists in detail</topic>
	<topic id="shutdownserver" href="shutdownserver.html">Shut down a server</topic>

</relatedtopics>

What number do you think gets displayed by the alert?

The answer is different depending on which browser you use. In IE you get 5 (which is what I had expected), but in Firefox you get 11. Why?

The answer is that Firefox covertly adds a #text node for each area of whitespace between the child nodes that are visible in your XML. So in the above XML there's actually an invisible child node before the first topic element, another one between each topic element, and another after the last topic element - making 11 nodes in total.

If I'd written the XML like this:

<?xml version="1.0" ?>

<relatedtopics><topic id="imadmin_createrolegroup" href="createrolegroup.html">Create a role group</topic><topic id="imadmin_usesettingseditor" href="usesettingseditor.html">Use the Settings editor</topic><topic id="imadmin_turnonuserfriendlydatesinsearchqueries" href="turnonuserfriendlydatesinsearchqueries.html">Turn on user-friendly dates in search queries</topic><topic id="imadmin_systempicklistsindetail" href="systempicklistsindetail.html">The system picklists in detail</topic><topic id="imadmin_shutdownserver" href="shutdownserver.html">Shut down a server</topic></relatedtopics>

I would have got 5 in both browsers.

This is nicely explained, with a useful diagram, in an article called "Whitespace in the DOM" at http://developer.mozilla.org/en/docs/Whitespace_in_the_DOM.

Comments are closed.