Sunday, May 27, 2012

Implement Your Own JavaScript getElementsByClassName method

I have started reading the second edition of Jeremy Keith's and Jeffrey Sambells's book "DOM Scripting: Web Design with JavaScript and the Document Object Model."

 In Chapter 3, under the section "Nodes -> Getting Elements", sub-section "getElementsByClassName", the author suggests implementing a custom getElementsByClassName method for JavaScript engines which do not support it natively.

 Although most current engines seem to support getElementsByClassName, the code snippet provided in the book for the custom method does not work properly. I re-wrote some of the implementation to get the desired result:

function getElementsByClassName(node, classname){
    if(node.getElementsByClassName){
        return node.getElementsByClassName(classname);
    } else { 
        var results = new Array();
        var elemsOnPage = document.getElementsByTagName("*");
        var len = elemsOnPage.length;
        var i;
        for(i = 0; i < len; i++){
            if(elemsOnPage[i].className && elemsOnPage[i].className == classname){
                results[results.length] = elemsOnPage[i];
     }
        }
        return results;
    }
}
The original code did not check if className was defined and used indexOf instead of a string comparison. Any feedback or suggestions are much appreciated and I will try to pass the information to the authors. You can buy the book here at amazon if you are interested in these topics. I highly recommend it.