0

I often see in many javascript samples here, getting the object name by:

 var id = document.getElementById("MyId");
 id.play();  //MyId above is that of an <audio> element

In my javascript code, on chromebook and android, I can directly use the element id as object name without the first line above. Are ids now automatically mapped into the javascript namespace? For example, in the html I have,

 <audio id="MyId" controls>

Then in the javascript, I can use the code below successfully:

 MyId.play();

Could somebody please explain why I do not need to execute the getElementById() first?

Thank

CqN
  • 139
  • 1
  • 8
  • 1
    This was a shortcut implemented by some browsers that I do not think is a standard behavior universally implemented. Plus, any library or piece of your own code that implements a global variable with the same name as one of these id values will replace the id variable. It was a bad idea to implement it that way and IMO it's a bad idea to code to it. – jfriend00 Jan 25 '14 at 04:36
  • 1
    and [Should the id of elements be made global variables? And](http://stackoverflow.com/q/6381425/218196) – Felix Kling Jan 25 '14 at 04:36
  • 1
    _"Are ids now automatically mapped into the javascript namespace?"_ - This isn't a new feature with html5 (as sort of implied by your "now"), but as the other comments indicate it won't work in all browsers. – nnnnnn Jan 25 '14 at 04:37
  • I think this auto name mapping does take place for all the elements. Perhaps only for the newer elements? For things like
    one may have to use getElementById() in js; I have not verified this, but I do see in my code a lot of the above method usage.
    – CqN Jan 26 '14 at 00:26

0 Answers0