Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between getElementById and simply using an element's ID as a variable?

Can someone tell me the difference between calling an HTML elment with id="myDomObect"?:

var myObj = document.getElementById('myDomObect');

&

var myObj = myDomObect;
like image 862
BeachInCalifornia.com Avatar asked Oct 15 '25 17:10

BeachInCalifornia.com


1 Answers

Use the first form or a wrapper such as jQuery. The second form,

var myObj = myDomObect;

Translates to

var myObj = window["myDomObect"];

This "works" because of an old, old hack in which ID's were exposed as global window properties (IIRC this was a misfeature from the start) and thus we are still blessed with the behavior 20 years later.. and yes, it will work in the very latest Chrome.

However, such a shorthand should not be used for multiple reasons:

  1. It will not work as originally written in "strict mode" (but it will work with the second form)

  2. It does not convey the operation - namely that a DOM element is requested/fetched (by ID).

  3. It does not work for IDs that collide with window properties; eg. <div id=history></div> would result in "unexpected behavior" if accessed this way. (This doesn't affect getElementById code that correctly uses local var variables in a function.)

  4. Behavior is not defined when duplicate IDs exist in the document (which is allowed); the behavior for getElementById has been codified in by DOM 4: "getElementById(elementId) method must return the first element [with the ID], in tree order.."


See also:

  • Do DOM tree elements with ids become global variables?
like image 152
user2864740 Avatar answered Oct 18 '25 08:10

user2864740