8

Accidentally, I noticed I could use the id of an HTML element in JavaScript code. So instead of this:

var myCanvas = document.getElementById('myCanvas');
myCanvas.width = '600';
myCanvas.height = '400';

I could simply not even have the first line, because the variable myCanvas apparently already exists!

myCanvas.width = '600';
myCanvas.height = '400';

This is nice, but can I rely on it? Is this normal behavior that I can expect in all modern browsers? I don't care about any browsers before IE9.

at.
  • 50,922
  • 104
  • 292
  • 461
  • Related: http://stackoverflow.com/questions/12510399/do-i-really-need-to-call-getelementbyid – megawac Nov 04 '13 at 20:32
  • I doubt it's common behavior. But, you should re-search this. – Joe Simmons Nov 04 '13 at 20:33
  • Its common behaviour but should not be used too often see http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here – megawac Nov 04 '13 at 20:34

3 Answers3

6

In the early days of browser scripting, IE made ID and NAME attribute values into properties of the global object that referenced the related elements. That was widely considered a "bad thing", but was copied by most other browsers in order to be compatible with IE (most sites at the time were written almost exclusively for IE, which had about 95% user share).

Then came open standards and a concerted effort to support them. Now no one with any sense uses it, though it's still supported by probably all browsers in use.

Note that declared global variables of the same name take precedence over a same–named or ID'd element.

RobG
  • 142,382
  • 31
  • 172
  • 209
3

I'm going to refer you to this answer and mention that this is not standard behaviour. This behaviour is supported by all browsers (sans Firefox outside of quircks mode) but I would not recommend its use. This is not supported by firefox<14 in standards mode

Community
  • 1
  • 1
megawac
  • 10,953
  • 5
  • 40
  • 61
  • Do you have a link for the Firefox claim? This behaviour is supported by Firefox 24 in standards mode, and has been almost forever as far as I'm aware. There was a huge debate about whether Mozilla should support it back around version 1.0, but pragmatism won the argument. – RobG Nov 04 '13 at 22:30
  • @RobG I was incorrect, its been supported since firefox 14 http://tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/ – megawac Nov 04 '13 at 23:31
2

You can rely on it. But if the language running the site is ASP.NET, it is safer to use the ClientID. If the ID of the control changes, your code will adapt.

e.g. For Javascript running over ASP.NET

var myCanvas = document.getElementById("<%=myCanvas.ClientID%>");