As a response to Carst van der Molen, who commented on my latest article, I've written some tests to check where HTML elements go when you're leaving out
I’m using the word “tags”, because it are, in fact, only the tags that are left out of the document. The actual elements are inserted by the user agent.
Carst van der Molen made the following interesting statement:
I’ve written some quick tests to see what exactly happens to elements when you leave out the popular containing tags.
HEAD element, after which it prints the
nodeName of that childnode to the document.
Test results for Firefox
Interestingly, it apparently just makes some educated guesses of what goes where.
SCRIPT elements for example, go inside the
HEAD by default. Even if the
SCRIPT element resides at the very bottom of the document source!. The same is true for
Test results for Safari
Safari gives back some odd results. The
SCRIPT elements do not show up in the
HEAD element! To make it sure they really aren’t there, I’ve written another script. In Firefox, the word “SCRIPT” gets printed two times. In Safari, the page remains empty.
This was very unexpected to me, and I still don’t really understand why this happens.
Test results for Internet Explorer
IE versions 5, 6 and 7 all give the same results as Firefox.
Test results for Opera
It looks like Carst had a fair point when questioning the control one’s having over where elements go. The best thing to do is probably just to add the
BODY tags to your document when writing HTML. On the other hand; I can’t think of much examples where I absolutely need to know whether elements exist in the
HEAD or the
BODY. 9 times out of 10 I reference elements either by tag-name or id.
In conclusion I want to point out that the W3C validator makes the same educated guesses Firefox makes. Validate the following example and you’ll see the validator tells you it’s an invalid document (due to a
STYLE element being placed outside the
HEAD element). If, however, the
STYLE element comes before any other element that is considered to reside inside the
BODY, it does actually validate.