因为getElementByClassName不兼容IE8,如下function封装了支持IE8的getElementByClassName函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p class="haha">
dddddddddd
<p class="wawa">
ggggggg
</p>
</p>
<script>
function getElementsByClassName(element, names) {
if (element.getElementsByClassName) {
return element.getElementsByClassName(names);
} else {
var elements = element.getElementsByTagName('*');
var result = [];
var element,
classNameStr,
flag;
names = names.split(' ');
for (var i = 0; element = elements[i]; i++) {
classNameStr = ' ' + element.className + ' ';
flag = true;
for (var j = 0, name; name = names[j]; j++) {
if (classNameStr.indexOf(' ' + name + '') == -1) {
flag = false;
break;
}
}
if (flag) {
result.push(element);
}
}
return result;
}
}
var t=getElementsByClassName(document,'haha');
var b=getElementsByClassName(t,'wawa');
console.log(t);
console.log(b);
</script>
</body>
</html>
Uncaught TypeError: element.getElementsByTagName is not a function
请问问题出在哪?
ringa_lee2017-04-11 13:10:57
报错是因为element.getElementsByTagName
的element
是一个数组,不是节点对象。所以说
is not a function
我觉得这个方法的设计有点不合理,传入的参数(element, names)
的element
不要传数组,传一个父对象或者document就好使了。另外帮你简化一下代码,希望有助。
var getElementsByClassName = function(element, names) {
var result = [];
var element = element != undefined ? element : document;
var all = element.getElementsByTagName('*');
for(var i = 0;i < all.length; i++){
if ((new RegExp('(\\s|^)' + names + '(\\s|$)')).test(all[i].className)) {
result.push(all[i]);
}
}
return result;
}
var t = getElementsByClassName(document,'haha');
var b = getElementsByClassName(t[0],'wawa'); //不能传数组,一定要的话要判断是document还是数组,再去遍历
console.log(t);
console.log(b[0].innerHTML);
天蓬老师2017-04-11 13:10:57
var elements = element.getElementsByTagName('*');
// 这里的element你只考虑了他是一个节点的情况,那多个节点呢,非节点呢?
var t=getElementsByClassName(document,'haha');
var b=getElementsByClassName(t,'wawa'); // 这里你传进去的t不就是多个节点么