ie8兼容getELementsByClassName

//ie8兼容getElementsByClassName
function getElementsByClassName(className, root, tagName) {  
    if (root) {
        root = typeof root == "string" ? document.getElementById(root) : root;
    } else {
        root = document;
    }
    tagName = tagName || "*";
    // console.log(root)
    if (document.getElementsByClassName) {                 
        return root.getElementsByClassName(className);
    } else {
        var tag = root.getElementsByTagName(tagName);  
        var tagAll = [];            
        for (var i = 0; i < tag.length; i++) { 
            for (var j = 0, n = tag[i].className.split(' ') ; j < n.length; j++) { 
                if (n[j] == className) {
                    tagAll.push(tag[i]);
                    break;
                }
            }
        }
        return tagAll;
    }
}

root是它的父节点的名称,tagName是元素名,可写也可不写

使用方法:getElementsByClassName(class名称)

posted @ 2017-02-22 15:07  holdonBestrong  阅读(156)  评论(0编辑  收藏  举报