IE8 兼容 getElementsByClassName
IE8以下版本没有getElementsByClassName这个方法,以下是兼容写法
function ieGetElementsByClassName() {
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;
};
}
}
ieGetElementsByClassName();
这个方法会在IE8浏览器的document上挂载getElementsByClassName方法
,但是存在一个问题:
有一个已经获取到的元素,再通过类名获取子元素时会报错,比如
var idDom = document.getElementById(id)
idDom.getElementsByClassName(class) //idDom没有getElementsByClassName方法,会报错
解决办法:
function ieGetIdClass(id, classname) {
if (document.getElementsByClassName) {
if (id) {
var arrId = document.getElementById(id);
return arrId.getElementsByClassName(classname);
} else {
return document.getElementsByClassName(classname);
}
} else {
if (id) {
var arrId = document.getElementById(id);
var dom = arrId.getElementsByTagName("*");
var arr = [];
for (var i = 0; i < dom.length; i++) {
var txtArr = dom[i].className.split(" ");
for (var j = 0; j < txtArr.length; j++) {
if (txtArr[j] == classname) {
arr.push(dom[i]);
}
}
}
return arr;
}
}
}
//用法
var doms = ieGetIdClass(id,class) //获取id元素下的所有class子元素
做学习用,开发中建议使用jQuery
======================================= END ========================================