HTML DOM 導航
通過 HTML DOM,您能夠使用節(jié)點關(guān)系在節(jié)點樹中導航。
HTML DOM 節(jié)點列表
getElementsByTagName() 方法返回節(jié)點列表。節(jié)點列表是一個節(jié)點數(shù)組。
下面的代碼選取文檔中的所有 <p> 節(jié)點:
實例
<html><!DOCTYPE html> <html> <body> <p>Hello World!</p> <p>The DOM is very useful!</p> <script> x=document.getElementsByTagName("p"); document.write("The innerHTML of the second paragraph is: " + x[1].innerHTML); </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
注意:
下標號從 0 開始。
HTML DOM 節(jié)點列表長度
length 屬性定義節(jié)點列表中節(jié)點的數(shù)量。
您可以使用 length 屬性來循環(huán)節(jié)點列表:
實例
<html><!DOCTYPE html> <html> <body> <p>Hello World!</p> <p>The DOM is very useful!</p> <p>This example demonstrates the <b>length</b> property.</p> <script> x=document.getElementsByTagName("p"); for (i=0;i<x.length;i++) { document.write(x[i].innerHTML); document.write("<br>"); } </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
實例解析:
獲取所有 <p> 元素節(jié)點
輸出每個 <p> 元素的文本節(jié)點的值
導航節(jié)點關(guān)系
您能夠使用三個節(jié)點屬性:parentNode、firstChild 以及 lastChild ,在文檔結(jié)構(gòu)中進行導航。
請看下面的 HTML 片段:
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
首個 <p> 元素是 <body> 元素的首個子元素(firstChild)
<div> 元素是 <body> 元素的最后一個子元素(lastChild)
<body> 元素是首個 <p> 元素和 <div> 元素的父節(jié)點(parentNode)
firstChild 屬性可用于訪問元素的文本:
實例
<html><!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
DOM 根節(jié)點
這里有兩個特殊的屬性,可以訪問全部文檔:
document.documentElement - 全部文檔
document.body - 文檔的主體
實例
<html><!DOCTYPE html> <html> <body> <p>Hello World!</p> <div> <p>The DOM is very useful!</p> <p>This example demonstrates the <b>document.body</b> property.</p> </div> <script> alert(document.body.innerHTML); </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
childNodes 和 nodeValue
除了 innerHTML 屬性,您也可以使用 childNodes 和 nodeValue 屬性來獲取元素的內(nèi)容。
下面的代碼獲取 id="intro" 的 <p> 元素的值:
實例
<html><!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> txt=document.getElementById("intro").childNodes[0].nodeValue; document.write(txt); </script> </body> </html>
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
在上面的例子中,getElementById 是一個方法,而 childNodes 和 nodeValue 是屬性。
在本教程中,我們將使用 innerHTML 屬性。不過,學習上面的方法有助于對 DOM 樹結(jié)構(gòu)和導航的理解。