這樣我們就可以通過DOM提供給的方法、接口來訪問HTML內(nèi)容,而不需要單個元素一個一個的查詢。
DOM提供了幾個屬性可以容易的訪問樹結(jié)構(gòu)中的節(jié)點。如下
以parentNode、childNodes、previousSibling為例進行說明,看下面代碼
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標(biāo)題文檔</title><script language="javascript"> //顯示當(dāng)前節(jié)點的父節(jié)點 function showParentNode() { //獲得當(dāng)前節(jié)點對象 var myObj=document.getElementById("lilongsheng"); //查找父節(jié)點 var parent=myObj.parentNode; //顯示父節(jié)點名 alert(parent.nodeName); } //顯示孩子節(jié)點列表,返回類型為NodeList function showchild() { //獲得當(dāng)前節(jié)點對象 var myObj=document.getElementById("lilongsheng"); //查找節(jié)點的子節(jié)點列表 var child=myObj.childNodes; //循環(huán)顯示子節(jié)點列表 for (var i=0;i<child.length;i++) { alert(child[i].nodeName); } } //顯示下一個兄弟節(jié)點 function showSibling() { //獲得當(dāng)前節(jié)點對象 var myObj=document.getElementById("lilongsheng"); //查找下一個兄弟節(jié)點 var sibling=myObj.nextSibling; //顯示 alert(sibling.nodeName); }</script></head><body> <form> <ul id="lilong"> <li id="lilongsheng"> <a href="#" >標(biāo)題1</a> <a href="#" >標(biāo)題2</a> <a href="#" >標(biāo)題3</a> <a href="#" >標(biāo)題4</a> </li> <hr/> </ul> <input type="button" onclick="showParentNode()" value="獲取父標(biāo)簽名" /> <input type="button" onclick="showchild()" value="獲取子標(biāo)簽名" /> <input type="button" onclick="showSibling()" value="獲取兄弟標(biāo)簽名" /> </form></body></html>