getElementsByClassName的兼容方法很多,参照zxx,方法较简单:
getByClassName = function(classNames){
return this.querySelectorAll("." + classNames.trim().replace(/\s+/,"."));
};
if (!document.getElementsByClassName){
document.getElementsByClassName = getByClassName;
}
实际测试中,还有一种情况没有考虑:ele.getElementsByClassName
没有考虑,参照别人写的,又该重温下DOM相关的继承关系,解决办法如下:
if(!Element.getElementsByClassName){
Element.prototype.getElementsByClassName = getByClassName;
}
参考链接:
getElementsByClassName in ie8 [duplicate]
当然,以上方法对ie8有效,如需要支持iee6,7可以参照一下方法
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
var tabs = getElementsByClassName(document.body,'tab');
参考链接
javascript document.getElementsByClassName compatibility with IE