通常先使用getElementsByTagName("*")取出文檔中所有元素,然後進行遍歷,使用正則表達式找出匹配的元素放入一個數組返回。由於IE5不支持document.getElementsByTagName("*"),要使用分支document.all以防錯誤
下面的方法完美支持了document寫法
復制代碼 代碼如下:
if(!document.getElementsByClassName){
document.getElementsByClassName = function(className, element){
var children = (element || document).getElementsByTagName('*');
var elements = new Array();
for (var i=0; i<children.length; i++){
var child = children[i];
var classNames = child.className.split(' ');
for (var j=0; j<classNames.length; j++){
if (classNames[j] == className){
elements.push(child);
break;
}
}
}
return elements;
};
}
最終的方案為:
復制代碼 代碼如下:
var getElementsByClassName = function (searchClass, node,tag) {
if(document.getElementsByClassName){
var nodes = (node || document).getElementsByClassName(searchClass),result = [];
for(var i=0 ;node = nodes[i++];){
if(tag !== "*" && node.tagName === tag.toUpperCase()){
result.push(node)
}else{
result.push(node)
}
}
return result
}else{
node = node || document;
tag = tag || "*";
var classes = searchClass.split(" "),
elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
patterns = [],
current,
match;
var i = classes.length;
while(--i >= 0){
patterns.push(new RegExp("(^|\s)" + classes[i] + "(\s|$)"));
}
var j = elements.length;
while(--j >= 0){
current = elements[j];
match = false;
for(var k=0, kl=patterns.length; k<kl; k++){
match = patterns[k].test(current.className);
if (!match) break;
}
if (match) result.push(current);
}
return result;
}
}