getElementsByClassName
今天在网上看到的一个根据ClassName获取Elements的脚本,在此记录一下,以便日后使用。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 var getElementsByClassName = function(searchClass, node, tag) {
2 if (document.getElementsByClassName) {
3 return document.getElementsByClassName(searchClass)
4 } else {
5 node = node || document;
6 tag = tag || "*";
7 var classes = searchClass.split(" "),
8 elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag),
9 patterns = [],
10 returnElements = [],
11 current,
12 match;
13 var i = classes.length;
14 while (--i >= 0) {
15 patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
16 }
17 var j = elements.length;
18 while (--j >= 0) {
19 current = elements[j];
20 match = false;
21 for (var k = 0, kl = patterns.length; k < kl; k++) {
22 match = patterns[k].test(current.className);
23 if (!match) break;
24 }
25 if (match) returnElements.push(current);
26 }
27 return returnElements;
28 }
29 }
2 if (document.getElementsByClassName) {
3 return document.getElementsByClassName(searchClass)
4 } else {
5 node = node || document;
6 tag = tag || "*";
7 var classes = searchClass.split(" "),
8 elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag),
9 patterns = [],
10 returnElements = [],
11 current,
12 match;
13 var i = classes.length;
14 while (--i >= 0) {
15 patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
16 }
17 var j = elements.length;
18 while (--j >= 0) {
19 current = elements[j];
20 match = false;
21 for (var k = 0, kl = patterns.length; k < kl; k++) {
22 match = patterns[k].test(current.className);
23 if (!match) break;
24 }
25 if (match) returnElements.push(current);
26 }
27 return returnElements;
28 }
29 }
作者:舍长
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.