要遍历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