Reputation: 928
Look at the following JS code:
alert(myImgId.src);
and corresponding HTML:
<img id="myImgId" src="http://images4.wikia.nocookie.net/__cb20121128141533/logopedia/images/6/6f/Superman_logo.png"></img>
What I expect would happen:
A javascript error specifying that it cannot find variable myImgId
, basically a sort of NPE while accessing object src
of myImgId
.
What actually happens: Modern browsers(FF 17 & above, chrome) pick up the DOM element with the given ID automatically. Older versions of browsers like FF 10 throw an error as expected.
Can somebody explain what is happening over here?
Upvotes: 3
Views: 168
Reputation: 19573
I gleaned this from another SO question, the question is not really the same as your question, but the answer does answer your question:
Can I Use an ID as a Variable Name?
and here is the good stuff: (all quoted from Sidnicious' answer)
Making global variables automatically is considered bad practice because it can be difficult to tell, looking at some code, whether it is on purpose or you forgot to declare a variable somewhere. Automatic creation of global variables like this doesn’t work in ES5 strict mode and could be phased out phased out in future versions of ECMAScript.
In the browser JavaScript’s global scope is actually window. When you refer to document you get window.document. Best practice for creating a global variable in a browser is to add it to window (global in Node.js)....
...It turns out that most browsers create properties on window (hence global variables) for each id in the document. Many browsers don’t make them read-only, you can overwrite them with your own, but Internet Explorer does.
This is another reason global variables in JavaScript can be dangerous — one of your ids could match a read-only window property (today or in some future browser).
Upvotes: 2
Reputation: 12375
My guess is:
Since you did not declare the variable with var
, it is seen as a global variable (global to the entire window) and the browser is automatically hooking it up, since the ID is the same as the object name.
Upvotes: -1