javascriptdom

Can I access DOM element directly by id?


In javascript I always use document.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)


Solution

  • 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.