document.getElementsByClassName compatibility

Firefox 3 and Safari 3.1 introduce an important new compatibility problem for many webpages. The problem originates from Prototype.js’s document.getElementsByChildName function which is implemented like this:

if (!document.getElementsByClassName)
document.getElementsByClassName = function(instanceMethods){
// …

The problem is that the native browser implementation works differently from Prototype’s function which was created before the document.getElementsByClassName specification was written. The native implementation returns a live nodelist whilst Prototype’s function returned a object array.

This compatibility issue affects websites using versions of Prototype.js older than 1.6 as well as other scripts which have used the document.getElementsByClassName function (including Reflection.js versions 1.8 and older).

Prototype.js users should use $$ or Element#select instead.

For my script, Reflection.js, I have renamed my function to document.myGetElementsByClassName. Sure it’s ugly but it means we preserve compatibility with older browsers which don’t support the new document.getElementsByClassName function natively. Also, we don’t need to test for whether the browser supports the function natively (and use a different codepath depending on whether a nodelist/object is returned). The downsides of course are that we can’t benefit from the faster native implementation.

Anyway, hope this helps someone out there.

One thought on “document.getElementsByClassName compatibility

Leave a Reply

Your email address will not be published. Required fields are marked *