javascript - What is the difference between getElementById and simply using an element's ID as a variable? -
can tell me difference between calling html elment id="mydomobect"?:
var myobj = document.getelementbyid('mydomobect');
&
var myobj = mydomobect;
use first form or wrapper such jquery. sec form,
var myobj = mydomobect;
translates to
var myobj = window["mydomobect"];
this "works" because of old, old hack in id's exposed global window properties (iirc misfeature start) , still blessed behavior 20 years later.. , yes, will work in latest chrome.
however, such shorthand should not used multiple reasons:
it not work written in "strict mode" (but work sec form)
it not convey operation - namely dom element requested/fetched (by id).
it not work ids collide window properties; eg. <div id=history></div>
result in "unexpected behavior" if accessed way. (this doesn't impact getelementbyid code correctly uses local var
variables in function.)
behavior not defined when duplicate ids exist in document (which is allowed); behavior getelementbyid has been codified in dom 4: "getelementbyid(elementid) method must homecoming first element [with id], in tree order.."
see also:
do dom tree elements ids become global variables? javascript dom reference
No comments:
Post a Comment