IE不支持getElementsByClassName最终完美解决方案
目前可以这么解决,判断浏览器支不支持这个方法,如果支持就不管;如果不支持,就在document对象里加入getElementsByClassName这个方法,这样的写法有一个好处,即不管有没有原生函数你都不用去修改代码。
通常先使用getElementsByTagName("*")取出文档中所有元素,然后进行遍历,使用正则表达式找出匹配的元素放入一个数组返回。由于IE5不支持document.getElementsByTagName("*"),要使用分支document.all以防错误
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;
}
}