Prototype: selecting elements by id or name in Internet Explorer

Joor Loohuis, April 21, 2009, 10556 views.

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.

Tags: , , , ,

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.

Example code

Consider the following snippet of HTML:

<p><a name="news">start of news</a></p>
<div id="news">
Actual news...
</div>

Running JavaScript code like

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.

Cause

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.

Remedy

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.

References

Social networking: Tweet this article on Twitter Pass on this article on LinkedIn Bookmark this article on Google Bookmark this article on Yahoo! Bookmark this article on Technorati Bookmark this article on Delicious Share this article on Facebook Digg this article on Digg Submit this article to Reddit Thumb this article up at StumbleUpon Submit this article to Furl

Talkback

respond to this article