`
caniggia1986
  • 浏览: 151493 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

getElementsByClassName

 
阅读更多
//code ref  http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html
//支持 多class搜索   ie:getElementsByClassName("classA classB")
var getElementsByClassName = function (searchClass, node, tag) {
    var node = node || document;
    var tag = tag || "*";
    if (document.getElementsByClassName) {//尽量用原生方法
        var nodes = node.getElementsByClassName(searchClass),result = [];
        if (tag === "*") {//直接return
            return nodes;
        } else {
            for (var node  in nodes) {
                if (node.tagName === tag.toUpperCase()) {
                    result.push(node)
                }
            }
            return result
        }
    } else {
        var classes = searchClass.split(" "),
                elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag),
                patterns = [],
                current,
                match;
        var i = classes.length;
        while (i--) {
            patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
        }
        var j = elements.length;
        while (j--) {
            current = elements[j];
            match = false;
            for (var pattern in patterns) {
                match = pattern.test(current.className);
                if (!match)  break;
            }
            if (match)  result.push(current);
        }
        return result;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics