1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>通过class获取元素</title> 6 <style type="text/css"> 7 ul li{ list-style: none; height: 20px; padding: 10px;line-height: 20px;} 8 ul li.red{ background: #999;} 9 </style> 10 <script type="text/javascript"> 11 /* 12 //第一种 13 function getByClass(obj,attr){ 14 var aEle = obj.getElementsByTagName(\'*\'); 15 var arr = []; 16 for(var i=0;i<aEle.length;i++){ 17 if(aEle[i].className == attr){ 18 arr.push(aEle[i]); 19 } 20 } 21 return arr; 22 }*/ 23 /* 24 //第二种 25 function getByClass(obj,sClass){ 26 var aEle = obj.getElementsByTagName("*"); 27 var aRes = []; 28 for(var i=0;i<aEle.length;i++){ 29 if(aEle[i].className.indexOf(sClass) != -1){ 30 aRes.push(aEle[i]); 31 } 32 } 33 return aRes; 34 }*/ 35 function findAttr(obj,sClass){ 36 for(var i=0;i<obj.length;i++){ 37 if(obj[i] == sClass) return true; 38 } 39 return false; 40 } 41 function getByClass(obj,sClass){ 42 if(obj.getElementsByClass){//这个getElementsByClass不兼容Ie8以下的, 43 var aEle = obj.getElementsByClass(sClass); 44 return aEle; 45 }else{ 46 var aEle = obj.getElementsByTagName("*"); 47 var aRes = []; 48 for(var i=0;i<aEle.length;i++){ 49 var aTmp = aEle[i].className.split(\' \'); 50 if(findAttr(aTmp,sClass)){ 51 aRes.push(aEle[i]); 52 } 53 } 54 return aRes; 55 } 56 } 57 window.onload = function(){ 58 var oDiv = document.getElementById("div1"); 59 var oUl = getByClass(oDiv,\'ul1\'); 60 var aLi = getByClass(oUl[0],\'red\'); 61 alert(aLi.length); 62 } 63 </script> 64 </head> 65 <div id="div1"> 66 <ul class="ul1"> 67 <li class="red">11111</li> 68 <li>22222</li> 69 <li class="red blue">3333</li> 70 <li>55555</li> 71 <li class="red">5555</li> 72 <li>6666</li> 73 </ul> 74 </div> 75 </html>
javascript不像Jquery那样可以很容易的获取元素,今天写了一个小方法Javascript通过class获取元素
1.用\'==\'来判断,这个判断如果class有多个会获取不到
2.用indexOf来判断,这个判断如果class有包含你要的找的class也会获取到,如:你要找class=\'test\',但是有一个class=\'tests\'也会被获取到
3.这个不会出错