As mentioned in the earlier answer this behavior is known as named access on the window object. The value of the name
attribute for some elements and the value of the id
attribute for all elements are made available as properties of the global window
object. These are known as named elements. Since window
is the global object in the browser, each named element will be accessible as a global variable.
This was originally added by Internet Explorer and eventually was implemented by all other browsers simply for compatibility with sites that are dependent on this behavior. Interestingly, Gecko (Firefox's rendering engine) chose to implement this in quirks mode only, whereas other rendering engines left it on in standards mode.
However, as of Firefox 14, Firefox now supports named access on the window
object in standards mode as well. Why did they change this? Turns out there's still a lot of sites that rely on this functionality in standards mode. Microsoft even released a marketing demo that did, preventing the demo from working in Firefox.
Webkit has recently considered the opposite, relegating named access on the window
object to quirks mode only. They decided against it by the same reasoning as Gecko.
So… crazy as it seems this behavior is now technically safe to use in the latest version of all major browsers in standards mode. But while named access can seem somewhat convenient , it should not be used.
Why? A lot of the reasoning can be summed up in this article about why global variables are bad. Simply put, having a bunch of extra global variables leads to more bugs. Let's say you accidentally type the name of a var
and happen to type an id
of a DOM node, SURPRISE!
Additionally, despite being standardized there are still quite a few discrepancies in browser's implementations of named access.
- IE incorrectly makes the value of the
name
attribute accessible for form elements (input, select, etc).
- Gecko and Webkit incorrectly do NOT make
<a>
tags accessible via their name
attribute.
- Gecko incorrectly handles multiple named elements with the same name (it returns a reference to a single node instead of an array of references).
And I'm sure there's more if you try using named access on edge cases.
As mentioned in other answers use document.getElementById
to get a reference to a DOM node by its id
. If you need to get a reference to a node by its name
attribute use document.querySelectorAll
.
Please, please do not propagate this problem by using named access in your site. So many web developers have wasted time trying to track down this magical behavior. We really need to take action and get rendering engines to turn named access off in standards mode. In the short term it will break some sites doing bad things, but in the long run it'll help move the web forward.
If you're interested I talk about this in more detail on my blog - https://www.tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/.