<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>push</title>
<style type="text/css">
*{
margin: 0 auto;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div class="demo"></div>
<script type="text/javascript">
console.log(getClass("demo").length);
function getClass(classname){
if(document.getElementsByClassName){
return document.getElementsByClassName(classname);
}
var arr =[];
var bom = document.getElementsByTagName("*");
for(var i=0; i<bom.length; i++){
if(bom[i].className == classname ){
arr.push(bom[i]);
}
}
return arr;
}
</script>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>push</title>
<style type="text/css">
*{
margin: 0 auto;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div class="demo"></div>
<script type="text/javascript">
//因为IE6,IE7浏览器不支持ClassName获取元素,所有采用以下方式:先做判断,识别ClassName的直接返回classname
//不识别的话,就直接获取所有元素,在循环得出元素中有classname的元素,都追加到数组arr,并作为函数的返回值(返回值取代函数名和参数(我是这样理解的))。。 getClass("demo")=arr getClass("demo").length=arr.length
console.log(getClass("demo").length);
function getClass(classname){
if(document.getElementsByClassName){
return document.getElementsByClassName(classname);
}
var arr =[];
var bom = document.getElementsByTagName("*");
for(var i=0; i<bom.length; i++){
if(bom[i].className == classname ){
arr.push(bom[i]);
}
}
return arr;
}
</script>
</body>
</html>