要遍歷dom樹全部的元素節點,主要是經過一個遞歸的過程來完成。例子以下:javascript <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">css <html>html <head>java <meta http-equiv="Content-Type" content="text/html; charset=utf-8">node <title>Untitled Document</title>dom <script type="text/javascript">函數 function countTags(n){ui var tags = "";this //獲取nodeType爲1的元素節點google if(n.nodeType ==1 ) tags += n.nodeName+"\n"; //遍佈節點的第一種寫法 // var children = n.childNodes; // for(var i=0; i<children.length; i++){ // tags += countTags(children[i]); // } //遍佈節點的第二種寫法 for(var m=n.firstChild; m!=null; m=m.nextSibling){ //調用函數自己的遞歸過程 tags += countTags(m); } return tags; } </script> </head> <body onload="alert(countTags(document));"> This is a <b>sample</b> document. </body> </html>
參考文獻:《javascript權威指南第五版》
另一個本身寫的導航欄效果:
第一部分是html代碼<body>... </body> 第二部分 :<head>...</head> <!--main--> <div id="main"> <ul> <li><a href="#" class="thisclass" onmouseover="fun2(this)">Hello</a></li> <li><a href="#" onmouseover="fun2(this)">Java</a></li> <li><a href="#" onmouseover="fun2(this)">CSS+DIV</a></li> <li><a href="#" onmouseover="fun2(this)" >網頁切圖</a></li> </ul> </div> <!--/main--> <script type="text/javascript" > function fun2(t){ var a1=document.getElementById("main").firstChild.childNodes; for(var i=0;i<a1.length;i++){ a1[i].firstChild.className=''; } t.className="thisclass"; } </script> |
@charset "utf-8"; body { background-color: #fff; font-size: 62.5%; margin: 0; padding: 0; } body * { font-size: 100%; } h1, h2, h3, h4, h5, h6 { font-weight: normal; } p { margin-bottom: 1.1em; margin-top: 0; } #main p.lastNode { margin-bottom: 0; } a:link img, a:visited img { border: none; } div.clearFloat { clear: both; font-size: 0; height: 0; line-height: 0px; } li.clearFloat { clear: both; } ul.symbolList { display: inline; float: left; list-style-type: none; margin: 0; padding: 0; } .AbsWrap { position: relative; width: 100%; } .rowWrap { width: 100%; } /*以上是fireworks生成的,(這是一個切圖練習的成果)*/ #main { background:url(images/1_110316234524_1_r2_c2.jpg); background-repeat:repeat-x; height:36px; margin: auto; width: 386px; border:1px solid gray; } #main ul{ float:left; height:32px; margin:0; padding:0; } #main ul a{ text-decoration:none; font-size:12px; color:#000; } #main ul li { /*background:url(images/1_110316234524_1_r3_c4.jpg);*/ margin-left:5px; line-height:28px; width:82px; height:32px; margin-top:5px; text-align:center; float:left; list-style-type:none; } #main ul li a.thisclass{ background:url(images/1_110316234524_1_r3_c4.jpg) no-repeat; display:block; float:left; height:32px; width:82px; text-align:center; }包含的圖片和css的完整項目: http://code.google.com/p/mydiary/downloads/list