Working on an idea for a simple HTMLElement wrapper I stumbled upon the following for Internet Explorer and Chrome:
For a given HTMLElement with an id in the DOM tree, it is possible to retrieve the <div> using its ID as a variable name or as a property of window. So for a <div> like
<div id="example">some text</div>
in Internet Explorer 8 and Chrome you can do:
alert(example.innerHTML); // Alerts "some text".
or
alert(window["example"].innerHTML); // Alerts "some text".
So, does this mean every element in the DOM tree is converted to a property on the global object? And does it also mean one can use this as a replacement for the getElementById method in these browsers?
What is supposed to happen is that ‘named elements’ are added as apparent properties of the
documentobject. This is a really bad idea, as it allows element names to clash with real properties ofdocument.IE made the situation worse by also adding named elements as properties of the
windowobject. This is doubly bad in that now you have to avoid naming your elements after any member of either thedocumentor thewindowobject you (or any other library code in your project) might want to use.It also means that these elements are visible as global-like variables. Luckily in this case any real global
varorfunctiondeclarations in your code shadow them, so you don’t need to worry so much about naming here, but if you try to do an assignment to a global variable with a clashing name and you forget to declare itvar, you’ll get an error in IE as it tries to assign the value to the element itself.It’s generally considered bad practice to omit
var, as well as to rely on named elements being visible onwindowor as globals. Stick todocument.getElementById, which is more widely-supported and less ambiguous. You can write a trivial wrapper function with a shorter name if you don’t like the typing. Either way, there’s no point in using an id-to-element lookup cache, because browsers typically optimise thegetElementByIdcall to use a quick lookup anyway; all you get is problems when elements changeidor are added/removed from the document.Opera copied IE, then WebKit joined in, and now both the previously-unstandardised practice of putting named elements on
documentproperties, and the previously-IE-only practice of putting them onwindoware being standardised by HTML5, whose approach is to document and standardise every terrible practice inflicted on us by browser authors, making them part of the web forever. So Firefox 4 will also support this.What are ‘named elements’? Anything with an
id, and anything with anamebeing used for ‘identifying’ purposes: that is, forms, images, anchors and a few others, but not other unrelated instances of anameattribute, like control-names in form input fields, parameter names in<param>or metadata type in<meta>. ‘Identifying’names are the ones that should be avoided in favour ofid.