2

I think this is absolutely ludicrous.

Given

HTML

<div id = "statCounter"></div>

Javascript

var statCounter = 5;

Executing

console.log(statCounter);
// logs <div id = "statCounter"></div>

How can this be? How absurd is this?!!? http://jsfiddle.net/rkkj58nw/

tdoakiiii
  • 376
  • 4
  • 13
  • http://jsfiddle.net/rkkj58nw/1/ ? – DaniP Feb 12 '15 at 21:32
  • Perhaps in this simple script you're right, but in my more complicated app I am setting (example) statCounter to some object like, statCounter = { prop1 : 1, prop2 : 2}; I pass the statCounter but instead it passes the Div! I console.log(statCounter.prop2) and get 2! I console.log(statCounter) and get the div! – tdoakiiii Feb 12 '15 at 21:34
  • 2
    see http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – bags Feb 12 '15 at 21:35
  • Okay so I am not crazy.. I just have never seen this in my humble 2 years of dev and cannot believe it would be implemented like this in the first place. – tdoakiiii Feb 12 '15 at 21:36
  • In his book "Secrets of the JavaScript Ninja" John Resig calls this behavior of browser as "Greedy IDs". Look it up. When you cannot avoid [this](http://www.joezimjs.com/javascript/dont-name-inputs-action-submit/) has a workaround – bp4D Feb 12 '15 at 21:49
  • https://html.spec.whatwg.org/#named-access-on-the-window-object – epascarello Feb 12 '15 at 21:50

1 Answers1

0

This was a feature implemented in IE (presumably as a syntax sugar to avoid peppering your code with getElementById() in the long ago days before frameworks, I'm talking 1999).

Originally, other browsers such as Netscape didn't have this misfeature. But at some point some non-IE browsers started to implement this feature to be compatible with corporate websites that uses IE specific features.

I'm not entirely sure but I believe by now this is specified in some standard (either ECMAScript or HTML5 or something else). So now all browsers implement this "feature".

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • Note that this answer has a better explanation on the history of this bug than my answer here: http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables?lq=1 – slebetman Feb 13 '15 at 02:26