4

Below is some sample code.

<body>
    <div id="wrapper" class="access">
        <form id="test">
            <input id="password"></input>
            <input type="submit"></input>
        </form>  
    </div>
    <script>
        console.log(password);
        alert(wrapper.className);
    </script>
</body>

The console log returns the DOM element with id password. The alert is "alert".

It works in normal code as well, e.g. var x = wrapper.className;

Surely this is not right? What is the point of document.getElementById, $('#password') or goog.dom.getElement if it just works like this? Are these functions just for legacy now?

It works in Firefox, Chrome and Safari, incidentally.

Nick
  • 5,995
  • 12
  • 54
  • 78
  • 1
    Some browsers define elements with IDs as global variables. IMO, use `getElementById`. – cookie monster Apr 16 '14 at 22:48
  • 2
    You can thank IE for that. They started it, others followed for compatibility. It's considered bad practice. Stick with `document.getElementById` or the equivalent in the libraries for which you provided examples. – Cᴏʀʏ Apr 16 '14 at 22:50
  • 2
    Possible duplicate of [JavaScript undefined variables are auto-defined?](http://stackoverflow.com/questions/21340666/javascript-undefined-variables-are-auto-defined), also: http://stackoverflow.com/questions/15767961/are-ids-for-an-html-element-always-available-from-the-window-object and http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here – David Thomas Apr 16 '14 at 22:52
  • @DavidThomas It may be a duplicate, but you need to know the answer to find it :) – Nick Apr 16 '14 at 22:53

2 Answers2

4

Backwards compatibility is the reason IDs are mapped to properties of the window.

It's also a major reason to avoid global variables - in fact some browsers will outright break if you try to use a global variable that's the same name as an element's ID.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
4

This answer should give you a lot to go on:

https://stackoverflow.com/a/6381766/944006

You shouldn't use these variables, and you DEFINITELY don't want to depend on them working correctly across browsers.

Community
  • 1
  • 1
Thad Blankenship
  • 2,242
  • 3
  • 16
  • 16