Pages

Monday, May 13, 2013

GetElementsBYClassName bug in IE

A while ago I was working with a checkBoxElement.click() type of function in which I had my client side javascript code identify the checkBoxElement through a HTMLNode.getElementsByClassName('myClassName') method.

This worked like charm with Chrome ( Chrome is the best :), unfortunately as expected this one had issues with the great Internet Explorer.

Eventually I had to scan through the web and with little effort I found the following nice function

function getElementsByClassName(node, classname) {
/* function obtained, modified and reused from
http://stackoverflow.com/questions/7410949/javascript-document-getelementsbyclassname-compatibility-with-ie
*/
var objectCollection = [];
        var re = new RegExp('(^| )'+classname+'( |$)');
        var els = node.getElementsByTagName("*");
        for(var i=0,j=els.length; i<j; i++)
            if(re.test(els[i].className))objectCollection.push(els[i]);
            return objectCollection;
        }

This worked well across both Chrome and IE. I am relieved :)

Hope this helps :)

No comments:

Post a Comment