It’s time for another technical article. Those of my readers who aren’t interested in this sort of thing can safely disregard this particular post.
There is a well known bug in the Internet Explorer implementation of the getElementById() method, which, contrary to the W3C standard, allows the method to return an element if the element’s id attribute _or_ its _name_ attribute matches the id the programmer is looking for. The standard example of why this is problem is as follows:
The error is caused because IE’s document.getElementById(‘description’) sees the meta tag with the name attribute set to “description” and since it treats name and id attributes as interchangeable, returns the meta tag instead of the textarea which actually has an id set to “description”. Arrggh!
In any case, I ran across a slick way of dealing with Internet Explorer’s badly implemented getElementById() method on a blog called Web Bug Track. The idea is to override IE’s native method with one that works according to W3C standards, like this:
However, I recently implemented this override workaround to the code for our web application, and doing so exposed another bug in IE7 that I hadn’t run across before. This bug is in its getAttribute() method .
The bug happens when you have a form in which there is an input with the name attribute set to “id”. For example,
But in IE7 you get instead:
Somehow, IE7’s getAttribute() method erroneously accesses the form input with the name “id” instead of the actual form element’s id! A little experimentation shows that you get the same IE7 result even if you use formElement2.id instead of the getAttribute() method. Fortunately, you can still get the correct form element id by using one of the following:
Our overridden getElementById() method depends on comparing the id of the element retrieved by IE7’s native method with the id that is being sought, but because of this bug in the getAttribute() method and the id property, even when the native method has returned the correct element the comparison fails because the id is the input element instead of the id attribute.
So, in order to make sure our getElementById() override for IE7 works properly, even when the element we are trying to get is a form containing an input element with the name attribute set to “id”, we have to revise our override method as follows: