Butterfish
by Butterfish

Clientside getElementsByClassName cross-browser implementation

Posted in Swell

We just came up with a “getElementsByClassName” cross-browser implementation quite interesting.

Most of the A-Grade browsers doesn’t support getElementsByClassName natively, and in this case you’ll have to write from scratch this method—excepted in one case: IE8.

Although it’s kinda annoying for a recent browser (which is still in RC1) to not support this W3C recommandation natively, it does at least support querySelectAll… in standards mode.
So we ran several tests to check the difference between IE8 in quirks/standards mode, which is actually noteworthy: 500% gain when using querySelectorAll, but still about twice slower compared to the native getElementsByClassName implementation in Firefox 3.0.6 ; but well, we didn’t expect that much.

function(className, root, tagName) {
    root = root || document.body;
    if (Swell.Core.isString(root)) {
        root = this.get(root);
    }
 
    // for native implementations
    if (document.getElementsByClassName) {
        return root.getElementsByClassName(className);
    }
 
    // at least try with querySelector (IE8 standards mode)
    // about 5x quicker than below
    if (root.querySelectorAll) {
        tagName = tagName || '';
        return root.querySelectorAll(tagName + '.' + className);
    }
 
    // and for others... IE7-, IE8 (quirks mode), Firefox 2-, Safari 3.1-, Opera 9-
    var tagName = tagName || '*', _tags = root.getElementsByTagName(tagName), _nodeList = [];
    for (var i = 0, _tag; _tag = _tags[i++];) {
        if (this.hasClass(_tag, className)) {
            _nodeList.push(_tag);
        }
    }
    return _nodeList;
}

Tags: ,

One Response to “Clientside getElementsByClassName cross-browser implementation”

  1. 1
    Libby Murray Says:

    Internet Explorer 8 is very good because it is as stable as Opera. I hate the previous versions of IE like IE6 because it hangs frequently. ~

Leave a Reply