<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta charset="utf-8">
<title>通过class获取元素</title>
<style>
#box div { width:100px; height:100px; border:1px solid red; margin:10px; }
#box .bar { background:#ccc; }
</style>
<script>
window.onload=function (){
    var oDiv=document.getElementById('box');
    
    var arr=getByClass(oDiv, 'bar');
    
    alert(arr.length);
};

function getByClass(oParent, sClassName)
{
    var res=[];
    var aTmp=oParent.getElementsByTagName('*');
    
    for (var i=0; i<aTmp.length; i++)
    {
        if (aTmp[i].className.indexOf(sClassName) != -1)
       { res.push(aTmp[i]); } }
return res; } </script> </head> <body> <div id="box"> <div class="bar item"></div> <div class="bar"></div> <div class="bar"></div> <div></div> <div></div> <p class="bar"></p> </div> </body> </html>

 

posted on 2014-11-24 14:32  高尔础础  阅读(4697)  评论(0编辑  收藏  举报