What is the difference between getElementById and just using the element id as a variable?

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

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

      

&

var myObj = myDomObect;

      

+3


source to share


2 answers


Use the first form or wrapper like jQuery. Second form,

var myObj = myDomObect;

      

Translates into

var myObj = window["myDomObect"];

      

This "works" because of an old old hack where the id was exposed as global properties of the window (IIRC was a bug from the start) and so we're still blessed with behavior 20 years later .. and yes it will work most modern Chrome.



However, such a transcript should not be used for several reasons:

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

  • It does not pass the operation - namely that the DOM element is requested / retrieved (by ID).

  • This does not work for identifiers that collide with window properties; eg. <div id=history></div>

    will result in "unexpected behavior" when accessing this path. (This does not affect the getElementById code, which correctly uses local variables var

    in the function.)

  • The behavior is undefined if duplicate identifiers exist in the document (which is permitted); the behavior for getElementById has been codified by DOM 4: "The getElementById (elementId) method must return the first element [with ID] in tree order."


See also:

+6


source


First, how the "real" DOM โ€‹โ€‹API works (another option document.querySelector("#myDomObject")

). Second, how browsers started to implement automatic lifting of id

'd elements , as IDs must be unique. In the "what do you think" twist, this can lead to hilarious conflicts where variables with the same name as HTML elements with an ID have no precedence, and the variable that you are using is suddenly an HTML element.



0


source







All Articles