一 介紹
遍歷文檔樹通過使用parentNode屬性、firstChild屬性、lastChild屬性、previousSibling屬性和nextSibling屬性來實現。
1、parentNode屬性
該屬性返回當前節點的父節點。
[pNode=]obj.parentNode
pNode:該參數用來存儲父節點,如果不存在父節點將返回“null”。
2、firstChild屬性
該屬性返回當前節點的第一個子節點。
[cNode=]obj.firstChild
cNode:該參數用來存儲第一個子節點,如果不存在將返回“null”。
3、lastChild屬性
該屬性返回當前節點的最后一個子節點。
[cNode=]obj.lastChild
cNode:該參數用來存儲最后一個子節點,如果不存在將返回“null”。
4、previousSibling屬性
該屬性返回當前節點的前一個兄弟節點。
[sNode=]obj.previousSibling
sNode:該參數用來存儲前一個兄弟節點,如果不存在將返回“null”。
5、nextSibling屬性
該屬性返回當前節點的后一個兄弟節點。
[sNode=]obj.nextSibling
sNode:該參數用來存儲后一個兄弟節點,如果不存在將返回“null”。
二 應用
遍歷文檔樹,在頁面中,通過相應的按鈕可以查找到文檔的各個節點的名稱、類型和節點值。
三 代碼
<head> <title>遍歷文檔樹</title> </head> <body > <h3 id="h1">三號標題</h3> <b>加粗內容</b> <form name="frm" action="#" method="get"> 節點名稱:<input type="text" id="na"/><br /> 節點類型:<input type="text" id="ty"/><br /> 節點的值:<input type="text" id="va"/><br /> <input type="button" value="父節點" onclick="txt=nodeS(txt,'parent');"/> <input type="button" value="第一個子節點" onclick="txt=nodeS(txt,'firstChild');"/> <input type="button" value="最后一個子節點" onclick="txt=nodeS(txt,'lastChild');"/><br> <input name="button" type="button" onclick="txt=nodeS(txt,'previousSibling');" value="前一個兄弟節點"/> <input type="button" value="最后一個兄弟節點" onclick="txt=nodeS(txt,'nextSibling');"/> <input type="button" value="返回根節點" onclick="txt=document.documentElement;txtUpdate(txt);"/> </form> <script language="javascript"> <!-- function txtUpdate(txt) { window.document.frm.na.value=txt.nodeName; window.document.frm.ty.value=txt.nodeType; window.document.frm.va.value=txt.nodeValue; } function nodeS(txt,nodeName) { switch(nodeName) { case"previousSibling": if(txt.previousSibling) { txt=txt.previousSibling; } else alert("無兄弟節點"); break; case"nextSibling": if(txt.nextSibling) { txt=txt.nextSibling; } else alert("無兄弟節點"); break; case"parent": if(txt.parentNode) { txt=txt.parentNode; } else alert("無父節點"); break; case"firstChild": if(txt.hasChildNodes()) { txt=txt.firstChild; } else alert("無子節點"); break; case"lastChild": if(txt.hasChildNodes()) { txt=txt.lastChild; } else alert("無子節點") break; } txtUpdate(txt); return txt; } var txt=document.documentElement; txtUpdate(txt); --> </script> </body>
四 運行結果
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
vue cli升級webpack4步驟詳解
vue 單頁應用前端路由如何配置
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com