通常先使用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; ichildren.length; i++){
var child = children[i];
var classNames = child.className.split(’ ’);
for (var j=0; jclassNames.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 !== "*"
tag = tag || "*";
var classes = searchClass.split(" "),
elements = (tag === "*"
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; kkl; k++){
match = patterns[k].test(current.className);
if (!match) break;
}
if (match) result.push(current);
}
return result;
}
}