给class添加id封装

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport"
 6           content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9     <style>
10         div{
11             width: 100px;
12             height: 100px;
13             background: pink;
14             margin: 10px;
15         }
16     </style>
17 </head>
18 <body>
19 <div></div>
20 <div class="demo"></div>
21 <div class="test"></div>
22 <div class="demo test one"></div>
23 <div class="demo one"></div>
24 <div></div>
25 <div id="one">
26     <div class="demo test one"></div>
27     <div class="demo one"></div>
28     <div class="test"></div>
29     <div class="demo"></div>
30     <div></div>
31 </div>
32 <div class="demo"></div>
33 
34 </body>
35 </html>
36 <script>
37     // document.getElementsByClassName()方法存在兼容性问题。不支持IE6,7,8,因此需要对其兼容性进行封装;
38     window.onload=function(){
39         // 默认第一个应该是class
40         function getClass(classname,id) {
41             if(document.getElementsByClassName){
42                 if(id)
43                 {
44                     var eleId=document.getElementById(id);
45                     return eleId.getElementsByClassName(classname);
46                 }
47                 else{//没有id
48                     return document.getElementsByClassName(classname);
49                 }
50             }
51             // 不支持情况也分为有没有id
52             if(id){
53                 var eleId=document.getElementById(id);
54                 var dom=eleId.getElementsByTagName('*');
55             }else{
56                 var dom=eleId.getElementsByTagName('*');
57 
58             }
59             var arr=[];
60             for(var i=0;i<dom.length;i++ ){
61                 var txtarr=dom[i].className.split(' ');
62                 for(var j=0;j<txtarr.length;j++){
63                     if(txtarr[j].className==classname)
64                     {
65                         arr.push(dom[i]);
66                     }
67                 }
68             }
69             return arr;
70         }
71        // console.log(getClass('test','one'));
72         var aa=getClass('test','one');
73         for(var i=0;i<aa.length;i++){
74             aa[i].style.backgroundColor='purple';
75         }
76     }
77 </script>

 

posted @ 2017-12-28 22:35  前端极客  阅读(734)  评论(0编辑  收藏  举报