這樣我們就可以通過DOM提供給的方法、接口來訪問HTML內容,而不需要單個元素一個一個的查詢。
DOM提供應用程序環境的一種標準程序處理接口,這是一種HTML和XML文件的標準API,可以再網絡上交換數據。
以parentNode、childNodes、previousSibling為例進行說明,看下面代碼
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標題文檔</title><script language="javascript"> //顯示當前節點的父節點 function showParentNode() { //獲得當前節點對象 var myObj=document.getElementById("lilongsheng"); //查找父節點 var parent=myObj.parentNode; //顯示父節點名 alert(parent.nodeName); } //顯示孩子節點列表,返回類型為NodeList function showchild() { //獲得當前節點對象 var myObj=document.getElementById("lilongsheng"); //查找節點的子節點列表 var child=myObj.childNodes; //循環顯示子節點列表 for (var i=0;i<child.length;i++) { alert(child[i].nodeName); } } //顯示下一個兄弟節點 function showSibling() { //獲得當前節點對象 var myObj=document.getElementById("lilongsheng"); //查找下一個兄弟節點 var sibling=myObj.nextSibling; //顯示 alert(sibling.nodeName); }</script></head><body> <form> <ul id="lilong"> <li id="lilongsheng"> <a href="#" >標題1</a> <a href="#" >標題2</a> <a href="#" >標題3</a> <a href="#" >標題4</a> </li> <hr/> </ul> <input type="button" onclick="showParentNode()" value="獲取父標簽名" /> <input type="button" onclick="showchild()" value="獲取子標簽名" /> <input type="button" onclick="showSibling()" value="獲取兄弟標簽名" /> </form></body></html>
分別獲得當前標簽的父標簽、子標簽、兄弟標簽,其余方法不再累述,可以使用這些簡單的方法實現對DOM文檔模型里的元素進行增、刪、改、查,操作DOM文檔。