Here’s an interesting DOM test-case I ran across inadvertently yesterday.
For the purpose of this post assume the following markup:
If I use
document.documentElement.firstChild I don’t get consistent behavior. In Firefox and IE I get the
<head/> element, which is what I was initially expecting. In WebKit (Safari/Chrome) and Opera. I get the HTML comment which I wasn’t.
I think WebKit and Opera are technically correct on this as the DOM Level 2 specs state:
COMMENT_NODE is a node and therefore should have been first. As for the position of the comment, the document is valid HTML5 and also is valid as XHTML 1.0 Strict and HTML 4 Strict. My interpretation is that this means indeed the comment is the first valid node in the
One of the reasons why I even thought to use
document.documentElement.firstChild is that I saw Google doing it the other day for the new asynchronous tracking code for Google Analytics (currently in beta). Originally the code was:
The new code seems a bit more resilient. They also got rid of the longhand
ga.setAttribute in favor of just
ga.async and added the
There is a test case for anyone who wants to try it. I haven’t found a relevant Mozilla bug.