getElementsByClassName

1706 단어 element

//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;
    }
}

좋은 웹페이지 즐겨찾기