<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>获取classname</title> </head> <script type="text/javascript"> window.onload=function(){ function getClassName(oParent,sClass){ var aEle=oParent.getElementsByTagName('*'); var aResult=[]; for (var i = 0; i < aEle.length; i++) { if(aEle[i].className=sClass){ aResult.push(aEle[i]); } } return aResult; } alert("a"); var oUl=document.getElementsByTagName("ul"); var oli=getClassName(oUl,"main"); } </script> <body> <ul id="name"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </body> </html>
就是var oUl=document.getElementsByTagName("ul");li的父元素ul只能通过Id获取,不能通过tagname获取,否则就报错
trinidy