Saturday 15 March 2014

javascript - Do DOM tree elements with ids become global variables? -



javascript - Do DOM tree elements with ids become global variables? -

working on thought simple htmlelement wrapper stumbled upon next internet explorer , chrome:

for given htmlelement id in dom tree, possible retrieve div using id variable name. div like

<div id="example">some text</div>

in internet explorer 8 , chrome can do:

alert(example.innerhtml); //=> 'some text'

or

alert(window['example'].innerhtml); //=> 'some text'

so, mean every element in dom tree converted variable in global namespace? , mean 1 can utilize replacement getelementbyid method in these browsers?

what supposed happen ‘named elements’ added apparent properties of document object. bad idea, allows element names clash real properties of document.

ie made situation worse adding named elements properties of window object. doubly bad in have avoid naming elements after fellow member of either document or window object (or other library code in project) might want use.

it means these elements visible global-like variables. luckily in case real global var or function declarations in code shadow them, don't need worry much naming here, if seek assignment global variable clashing name , forget declare var, you'll error in ie tries assign value element itself.

it's considered bad practice omit var, rely on named elements beingness visible on window or globals. stick document.getelementbyid, more widely-supported , less ambiguous. can write trivial wrapper function shorter name if don't typing. either way, there's no point in using id-to-element lookup cache, because browsers typically optimise getelementbyid phone call utilize quick lookup anyway; problems when elements alter id or added/removed document.

opera copied ie, webkit joined in, , both previously-unstandardised practice of putting named elements on document properties, , previously-ie-only practice of putting them on window being standardised html5, approach document , standardise every terrible practice inflicted on browser authors, making them part of web forever. firefox 4 back upwards this.

what ‘named elements’? id, , name beingness used ‘identifying’ purposes: is, forms, images, anchors , few others, not other unrelated instances of name attribute, control-names in form input fields, parameter names in <param> or metadata type in <meta>. ‘identifying’ names ones should should avoided in favour of id.

javascript dom global-variables getelementbyid identifier

No comments:

Post a Comment