My Favorite JavaScript Oddity: document.all
In the dusty annals of the browser are many artifacts from the days before standards bodies and modern JavaScript frameworks.
- The User Agent string
- MooTools polluting the Array prototype
- Everything that behaves differently without strict mode
But by far my favorite bit of “WTF JavaScript!” is document.all.
History
Internet Explorer implemented document.all before document.getElementById existed. It provides several ways to access DOM elements on the page:
// As an array of all elements on the page in
// depth-first order.
document.all[0] // <html>
// As an object with element IDs as keys.
document.all['content'] // <div id="content">
// As a function that returns an element with
// the passed ID.
// Works the same as document.getElementById()
document.all('content') // <div id="content">Since this was an Internet Explorer-only API, it didn't work in other browsers. However, since Internet Explorer had such market dominance, many web developers neglected to test their code on other browsers:
// Throws if not on IE, but everyone uses IE!
// And they always will!
alert(document.all['username'])Other browsers wanted these websites to work, so they also implemented document.all.
The Problem
Since initially, document.all only existed in Internet Explorer, developers used its existance for browser detection:
if (document.all) {
// Internet Explorer specific code
var activeX = new ActiveXObject("name")
} else {
// Code for other browsers
}Although other browsers supported document.all, they didn't support everything that Internet Explorer did. So they needed to support document.all without it triggering the Internet Explorer browser detection.
The Solution
Make document.all falsy!
Boolean(document.all) // falseNow it fails feature detection, but still works if you try to use it anyway.
document.all is an object
document.all is an array
document.all is a function
and document.all is falsy!