Skip to content Skip to sidebar Skip to footer

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;

Solution 1:

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:

Solution 2:

The first is how the "real" DOM API works (another option is document.querySelector("#myDomObject")). The second is how browsers have started implementing automatic hoisting of id'd elements, since ids are supposed to be unique. In a twist of "what were you thinking", this can lead to hilarious conflicts where variables that have the same name as HTML elements with an id don't take precedence and the variable you though you were using is suddenly an HTML element.

Post a Comment for "What Is The Difference Between Getelementbyid And Simply Using An Element's Id As A Variable?"