Q: How many childNodes does an empty <div> element have?

A: It depends how you write the empty div. This is a valid XHTML page, (you can check for yourself with the W3C validator) that contains two empty divs expressed as follows:

<div />

The divs are below this paragraph.

The divs are above this paragraph.

In XML, of which XHTML is an application, the first form is semantically equivalent to the second. I can't find anything in the XHTML specification that forbids the short form of writing an element, or says that it should be treated any differently by a user agent.

According to this user agent (unknown):


In tests, Firefox 1.07 (Windows and Linux), Internet Explorer 6 (Win) and Opera 8.5 (Win) give an incorrect, nonzero value for document.getElementsByTagName('div')[0].childNodes.length. The same browsers all give the correct value of zero for document.getElementsByTagName('div')[1].childNodes.length.

It seems that the browsers treat the first div, using the short form, as not being closed. So they think it contains everything after the element is actually closed. Firefox still thinks it is rendering in "Standards compliance mode". You can see this more clearly by using the debug scripts below. Note how this bug has implications on styling as well as scripting. The workaround is to always use the semantically equivalent longer form.

Reported to QuirksMode by Day Barr on 14th October 2005. Based on blog entry of 13th October.