3

Recently I have noticed something strange in my friends code. At first I thought that it was a mistake, but then I tested it and it seems to work. Please check out this simple code (notice "button_test.click()"):

<html>
 <head>
  <script>
   var test = function(){ 
    alert('hello');
   }
  </script>

 </head>
 <body>
  <button id="button_test" onclick="test();">click!</button>

  <script>
   button_test.click();
  </script>
 </body>
</html>

Why DOES it work? Where the "button_test" object is defined? I thought that I have to write document.getElementById("button_test") or $("#button_test") using jQuery to get a HTML element, but it seems to be unnecessary. Interestingly I get message "ReferenceError: button_test is not defined" when I move "button_test.click();" line to header.

  • 4
    Internet Explorer has always (or at least for a very long time) exposed element id values as global symbols (properties of the `window` object) that reference the DOM element. Other browsers over the years adopted the same practice. Personally I think it's an absolutely terrible idea, but there you go. – Pointy Mar 24 '15 at 20:19
  • 1
    Check out [this question](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) for more info why this happens (and why its a bad idea to rely on this behavior). – Bryant Miano Mar 24 '15 at 20:19

2 Answers2

1

JavaScript is full of things that "work" but aren't a good idea to use.

Use this instead:

document.getElementById('button_test')

or make sure that button_test is defined before ever using it:

if(!window.button_test) button_test = document.getElementById('button_test');
0

It was originally undefined behaviour, but since a lot of code was written that came to rely on it, the browser vendors implemented it and now HTML5 spec does give a definition for this.

Don't rely on it, because the behaviour is unpredictable, and it makes the code much less readable.

See http://www.2ality.com/2012/08/ids-are-global.html

Dan Blows
  • 20,846
  • 10
  • 65
  • 96