HTML DOM 導航
通過HTML DOM,您能夠使用節點關係在節點樹中導航。
HTML DOM 節點列表
getElementsByTagName()方法返回節點列表 。 節點列表是一個節點數組。
下面的代碼選取文檔中的所有<p> 節點:
注意:
下標號從0 開始。
HTML DOM 節點列表長度
length 屬性定義節點列表中節點的數量。
您可以使用length 屬性來循環節點列表:
實例
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
嘗試一下»
實例解析:
- 獲取所有<p> 元素節點
- 輸出每個<p> 元素的文本節點的值
導航節點關係
您能夠使用三個節點屬性:parentNode、firstChild 以及lastChild ,在文檔結構中進行導航。
請看下面的HTML 片段:
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</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> 元素的父節點(parentNode)
firstChild 屬性可用於訪問元素的文本:
實例
<html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
嘗試一下»
DOM 根節點
這裡有兩個特殊的屬性,可以訪問全部文檔:
- document.documentElement - 全部文檔
- document.body - 文檔的主體
實例
<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>
<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 屬性來獲取元素的內容。
下面的代碼獲取id="intro" 的<p> 元素的值:
實例
<html>
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
嘗試一下»
在上面的例子中,getElementById 是一個方法,而childNodes 和nodeValue 是屬性。
在本教程中,我們將使用innerHTML 屬性。 不過,學習上面的方法有助於對DOM 樹結構和導航的理解。