Prototype: selecting elements by id or name in Internet Explorer
April 21, 2009,
Selecting HTML elements by id using Prototype turns out to have a little quirk in Internet Explorer 7 and earlier, where the selected element may not have the specified value in the id attribute, but the name attribute in stead.
While developing some DHTML actions in a website using Prototype, I stumbled over an annoying, possibly hard to detect, problem. In turns out that while selecting an element by its id, Internet Explorer may not return the same element as other browsers.
Consider the following snippet of HTML:
<p><a name="news">start of news</a></p> <div id="news"> Actual news... </div>
var elm = $('news');
will return the div with the 'news' id in all W3C compliant browsers. However, in Internet Explorer 7 and older, the anchor element with the 'news' name will be returned, most likely leading to undesired behaviour.
Microsoft states in its documentation for the getElementById method:
"In IE7 mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results."
I consider this to be a bug in Internet Explorer, since the method name clearly suggests it will look for id attributes only. While it might be possible to work around it in Prototype, this will undoubtedly introduce bugs in applications relying on this feature.
The solution to solving conflicts between identical name and id values in Internet Explorer is to treat name attributes in HTML essentially as id attributes, and make sure these also have unique values. Merely differentiating in case is not sufficient. Strictly speaking, name and id attributes share the same namespace, and therefore are not supposed to occur more than once in a document. However, the code example above will validate in a HTML 4.01 Strict document.
NB: This bug is fixed in Internet Explorer 8, with the exception of its backward compatibility modes.
- Microsofts documentation on the getElementById method.