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


working on idea simple htmlelement wrapper stumbled upon following 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 use 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 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 naming here, if try 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 being 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 call use quick lookup anyway; problems when elements change 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 support this.

what ‘named elements’? id, , name being 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.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -