1 <script language="javascript" type="text/javascript"> 2 /*-------------封装开始------------------*/ 3 function GetId(id){return document.getElementById(id)} //通过ID获取对象 4 function GetTag(tag){return document.getElementsByTagName(tag)} //通过Tag获取对象 5 function GetChildTag(id,tag){return id.getElementsByTagName(tag)} //通过Tag获取ID的子对象 6 function GetClass(className){return getElementsByClassName(className)} //通过className获取对象 7 var $c=function(array){var nArray = [];for (var i=0;i<array.length;i++) nArray.push(array[i]);return nArray;}; 8 Array.prototype.each=function(func){for(var i=0,l=this.length;i<l;i++) {func(this[i],i);};}; 9 var getElementsByClassName=function(cn){ 10 var hasClass=function(w,Name){ 11 var hasClass = false; 12 w.className.split(' ').each(function(s){ 13 if (s == Name) hasClass = true; 14 }); 15 return hasClass; 16 }; 17 var elems =document.getElementsByTagName("*")||document.all; 18 var elemList = []; 19 $c(elems).each(function(e){ 20 if(hasClass(e,cn)){elemList.push(e);} 21 }) 22 return $c(elemList); 23 }; 24 /*-----------------封装结束---------------------*/ 25 window.onload=function(){ 26 GetTag("input")[0].onclick=function(){alert("id为test的div内容是:\n"+GetId("test").innerHTML)} 27 GetTag("input")[1].onclick=function(){alert("body里共有"+GetTag("li").length+"个li")} 28 GetTag("input")[2].onclick=function(){alert("DIV里共有"+GetChildTag(GetId("test"),"li").length+"个li")} 29 GetTag("input")[3].onclick=function(){alert("className为test2的内容是:\n"+GetClass("test2")[0].innerHTML+"\n"+GetClass("test2")[1].innerHTML)} 30 } 31 </script>
1 <div id="test" title="这是id=test的div"> 2 <ul title="div内第一个ul"> 3 <li>ccontent1</li> 4 <li>ccontent2</li> 5 <li>ccontent3</li> 6 <li>ccontent4</li> 7 </ul> 8 <ul class="test2" title="div内第二个ul,class=test2"> 9 <li>bcontent1</li> 10 <li>bcontent2</li> 11 <li>bcontent3</li> 12 </ul> 13 </div> 14 <ul class="test2" title="div外的ul,class=test2"> 15 <li>content1</li> 16 <li>content2</li> 17 </ul> 18 <input type="button" value="通过id获取" /> 19 <input type="button" value="通过tag获取" /> 20 <input type="button" value="通过id内tag获取" /> 21 <input type="button" value="通过className获取" />