Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the id of an HTML element as a variable in JavaScript? [duplicate]

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.

like image 246
at. Avatar asked Nov 04 '13 20:11

at.


1 Answers

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.

like image 68
RobG Avatar answered Sep 30 '22 12:09

RobG