Document Elements As Window Properties

If you name an element in your HTML document using the id attribute, and if the Window object does not already have a property by that name, the Window object is given a nonenumerable property whose name is the value of the id attribute and whose value is the HTMLElement object that represents that document element.

As we’ve already noted, the Window object serves as the global object at the top of the scope chain in client-side JavaScript, so this means that the id attributes you use in your HTML documents become global variables accessible to your scripts. If your document includes the element <button id="okay"/>, you can refer to that element using the global variable okay.

There is an important caveat, however: this doesn’t happen if the Window object already has a property by that name. Elements with the ids “history”, “location,” or “navigator”, for example, won’t appear as global variables, because those IDs are already in use. Similarly, if your HTML document includes an element whose id is “x” and you also declare and assign a value to the global variable x in your code, the explicitly declared variable will hide the implicit element variable. If the variable is declared in a script that appears before the named element, its existence will prevent the element from getting a window property of its own. And if the variable is declared in a script that appears after the named element, your explicit assignment to the variable overwrites ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.