Hacking getElementById correctly
No, no, no. I’m going to shout it out and keep saying it. Every so often
someone comes up with an improvement, a hack, that makes life easier for us.
The best-known include Tantek Çelik’s CSS hack for setting
element widths, which I won’t get into here, and a hack of unknown origin that “implements”
document.getElementById(String idname) through document.all in
browsers that don’t provide it, such as Internet Explorer 4.01.
The replacement looks like this. document.getElementById = document.all;
See anything odd? The main problem is that the
two methods behave differently in one specific case, when they return an element with a duplicate
id value.
Under the DOM specification,
when more than one element in the document has
the same id value, the method should return null
or the first element in the collection, which is what most browsers do.
document.all behaves differently. If
the id attribute is unique, it does return one object.
But if the value occurs more than once it returns an array, and that’s the problem.
If a script expects an object and treats it as such, then
receives an array (an Array object in particular), we should expect an error
or, in the worst case, a broken script.
This applies, of course, to people who don’t write valid pages.
A replacement that really works is straightforward.
document.getElementById = new Function("idname","kp=document.all(idname);if (kp==null) return null;if (kp.length)return document.all(idname)[0];return document.all(idname);");
All you need to do is check whether document.all returned an array or an object and, if it’s
an array, return its first member. It may not seem urgent and may not be a big deal, but a simple assignment doesn’t solve it correctly.
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio