首页 > 代码库 > js获取class 兼容

js获取class 兼容

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>封装getElementsByClassName</title>
 6 </head>
 7 <body>
 8 <div class="trsd demo">1111111111</div>
 9 <div>2222222222</div>
10 <div class="demo">3333333333333</div>
11 <div>44444444</div>
12 <div>55555555555</div>
13 <div>6666666666666</div>
14 <div class="demo2 tssr   demo">777777777777777</div>
15 <div>88888888888</div>
16 <div class="demo">999999999999999</div>
17 <div>0000000000000000</div>
18 <script>
19     function getClass(classname) {
20         if (document.getElementsByClassName) {
21             return document.getElementsByClassName(classname);
22         }
23 
24         var $elements = document.getElementsByTagName(‘*‘);
25         var arr = [];
26         for (var i = 0, j = $elements.length; i < j; i++) {
27             //如果有多个类 需要用空格隔开
28             var dom = $elements[i].className.split(" ");
29             for (var k = 0, l = dom.length; k < l; k++) {
30                 if (dom[k] == classname) {
31                     arr.push($elements[i]);
32                 }
33             }
34         }
35 
36         return arr;
37     }
38 
39     var test = getClass("demo");
40     console.log(test);
41     for(var i=0;i<test.length;i++){
42         test[i].style.background="#666";
43     }
44 
45 </script>
46 </body>
47 </html>

 

js获取class 兼容