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
headelement of a document is the firstheadelement that is a child of thehtmlelement, if there is one, ornullotherwise. Theheadattribute, on getting, must return theheadelement of the document (aheadelement ornull).
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 :)
Leave a comment
Comment on “The HTML5document.head DOM tree accessor”
Name *
Email *
Website
Your input will be parsed as Markdown.
Spammer? (Enter ‘no’) *

























