js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var getElementsByClassName = function(opts) {
var searchClass = opts.searchClass; // 存储要查找的类名
var node = opts.node || document; // 存储要出查找的范围
var tag = opts.tag || '*'; // 存储一定范围内要查找的标签
var result = [];
// 判断浏览器支不支持getElementsByClassName方法
if (document.getElementsByClassName) { // 如果浏览器支持
var nodes = node.getElementsByClassName(searchClass);
if (tag !== "*") {
for (var i = 0; node = nodes[i++];) {
if (node.tagName === tag.toUpperCase()) {
result.push(node);
}
}
} else {
result = nodes;
}
return result;
} else { // 使用IE8以下的浏览器能够支持该属性
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var i, j;
var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) { // 检测正则表达式
result[j] = els[i];
j++;
}
}
return result;
}
}

html代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>getElementsByClassName() 兼容浏览器方案</title>
<script src="domReady.js"></script>
<script src="getElementsByClassName.js"></script>
<script>
myReady(function(){
var myUl2 = document.getElementById("myUl2");
var r = getElementsByClassName({
searchClass: "light dark",
node: myUl2
});
console.log(r[0].innerHTML);
});
</script>
</head>
<body>
<ul id="myUl">
<li class="light">1</li>
<li class="light dark">2</li>
<li class="light">3</li>
</ul>
<ul id="myUl2">
<li class="light">1</li>
<li class="light dark">second</li>
<li class="light">3</li>
</ul>
</body>
</html>