Mathias Bynens

The HTML5 document.head DOM tree accessor

Published · tagged with HTML, JavaScript

One of the lesser known HTML5 JavaScript goodies is the document.head DOM tree accessor, which is a more efficient (and easier to type) alternative to document.getElementsByTagName('head')[0].

The head element of a document is the first head element that is a child of the html element, if there is one, or null otherwise. The head attribute, on getting, must return the head element of the document (a head element or null).

Native support for document.head is very easy to detect:

if (document.getElementsByTagName('head')[0] === document.head) {
// Native support
}

Emulating it is also very straightforward. Just put the following snippet in your JavaScript code:

document.head = document.head || document.getElementsByTagName('head')[0];

If you don’t care about JSLint booing at your code, you could also do this instead (which is slightly more efficient):

document.head || (document.head = document.getElementsByTagName('head')[0]);

After that, go ahead and use document.head all you want :)

About me

Hi there! I’m Mathias. I work on Chrome at Google. HTML, CSS, JavaScript, Unicode, performance, and security get me excited. Follow me on Twitter, Bluesky, and GitHub.

Comments

Framp wrote on :

if (!document.head)
document.head = document.getElementsByTagName('head')[0];

Simple is beautiful.

Raynos wrote on :

if (!document.head) {
document.head = document.getElementsByTagName("head")[0];
}

Curly braces are beautiful.

Adrusi wrote on :

if (!document.head) (function() {
document.head = document.getElementsByTagName("head")[0];
}());

Block scope is beautiful.

Lea Verou wrote on :

The problem with these polyfills is that on new iframes document.head still won’t exist, so they’re imperfect. Not sure how to solve that in a sensible manner though, but I’d really like to see a document.head polyfill one can really rely on.

wrote on :

Lea: That’s a fair point.

Personally I’m fine with just using the above snippet (it’s not really a polyfill in the strict sense of the word) once for every frame I need it for. Most of the time I need a reference to the <head> element in a given document, I end up caching it like this:

var head = document.head || document.getElementsByTagName('head')[0];

It’s so small and fast it doesn’t really hurt to repeat it for a different frame when needed.

MaxArt wrote on :

JSLint is a disgrace for all the JavaScript code artists.

It just doesn’t understand the power of JavaScript’s syntax.

Paul’s solution is the kind that I usually adopt.

Leave a comment

Comment on “The HTML5 document.head DOM tree accessor”

Your input will be parsed as Markdown.