Yes, it's universally supported, and it's even now in the HTML5 specification. Automatic global variables are created for every element with an id
(and many others with name
s).
I never rely on it, there are too many other things in the global namespace. But yes, it's defined behavior.
In a comment below you asked what happens when there's a conflict. More in my answer to another question, but there's an order to it. Automatic DOM globals are shadowed by declared global variables, in a couple of different ways. Here's an example:
// `example1` is a DOM automatic global
console.log(typeof example1); // object
console.log("example1" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example1")); // false
// We have both a DOM element with `example2` as its ID and also a
// `var`-declared global; the latter takes precedence
var example2;
console.log(typeof example2); // undefined
console.log("example2" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example2")); // true
// We have a DOM element with `example3` as its ID, a global object property
// with that name, and also a `let`-declared global variable; the latter wins
this.example3 = 42;
let example3;
console.log(typeof example3); // undefined
console.log("example3" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example3")); // true
.as-console-wrapper {
max-height: 100% !important;
}
<div id="example1"></div>
<div id="example2"></div>
<div id="example3"></div>
In a further comment you asked:
What of the case of conflicts with existing global members? For example, if I name my element "window" or "document"? Will my element take precedents over the existing global object member?
No, window
and document
and others are own properties of the Window object, but the automatic DOM globals are on its prototype (on compliant browsers; not IE11 or IIRC Legacy Edge). So its own properties win. To get at the automatic DOM globals, you'd have to go to window
's prototype:
// `window` here is still the global object
console.log(window === this); // true
var someVariableName;
console.log("someVariableName" in window); // true
// The automatic DOM global "window" is on its prototype:
console.log(Object.getPrototypeOf(window).window.tagName); // "DIV"
<div id="window"></div>
Of course, none of this is behavior you want to rely on. If you want to access a DOM element by its id
, use getElementById
(or querySelector
or similar).