function getElementsByClass(classnames){ var classobj = newArray(); var classint = 0; var tags =document.getElementsByTagName("*"); for(var i in tags){ if(tags[i].nodeType == 1){ if(tags[i].getAttribute("class") == classnames){ classobj[classint] = tags[i]; classint++; } } } return classobj; }
<!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>无标题文档</title> <scriptsrc="classtest.js"></script> <script> window.onload =function(){ var a = getElementsByClass("atest"); a[0].onmouseover = function(){ alert("class!!"); } } </script> <style> .atest{background:blue;width:200px;height:200px;margin:40px;color:white;} .btest{background:green;width:200px;height:200px;margin:40px;color:white;} </style> </head> <body> <divclass="atest">atestAAA</div> <divclass="btest">atestBBB</div> </html>