5

In javascript I always use docuemtn.getElementById to access DOM elements, but recently I accidentally accessed it using id only and it worked. Example:

<input id="element_id" type="text">

and in javascript

element_id.onclick=fun;

Is it correct code? Why does it work? (in all browsers I have)

Roman
  • 999
  • 3
  • 12
  • 23

2 Answers2

5

Yes, in some browsers, the elements are available as global variables named for their ID.

Don't use this "feature". It's non-standard, and not universally supported.

the system
  • 9,244
  • 40
  • 46
0

It will work in some browsers some of the time. For example, if you create the following element:

<div id="Math">I'm a math div!</div>

both Math and window.Math will return MathConstructor {}, since that's what the normal window.Math returns. (Tested in Chrome here)

ckersch
  • 7,507
  • 2
  • 37
  • 44