<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>封装Class类</title> <!-- 主要为了解决IE8以下浏览器不支持document.getElementsByClassName();(通过类名访问节点) 的问题; --> <style type="text/css"> div{background-color: pink;margin-top: 20px;width: 300px; height: 100px;} </style> <script type="text/javascript"> window.onload=function(){ function fn(classname){ if(document.getElementsByClassName){ // alert("该浏览器支持getElementsByClassName"); return document.getElementsByClassName(classname); }else{ var arr=[]; var divs=document.getElementsByTagName("*");//获取所有的div标签 for(var i=0;i<divs.length;i++){//遍历,挑出所有满足情况的div if(divs[i].className==classname){ arr.push(divs[i]); } } return arr; } } //ie中输出:哈哈 3 //ie中输出:undefined 3 alert(fn("demo")[1].value); alert(fn("demo").length); } </script> </head> <body> <div></div> <div></div> <div></div> <div class="demo" value="哈">123</div> <div></div> <div></div> <div class="demo" value="哈哈">456</div> <div></div> <div></div> <div></div> <div class="demo">789</div> </body> </html>