<!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>
时间: 2024-12-26 00:41:21