通过 HTML DOM,能够使用节点关系在节点树中导航。
1.HTML DOM 节点列表
getElementsByTagName() 方法返回节点列表。节点列表是一个节点数组。
下面的代码选取文档中的所有 <p> 节点:
1 <body>
2
3 <p>Hello World!</p>
4 <p>The DOM is very useful!</p>
5 <p>The DOM !</p>
6 <script>
7 x=document.getElementsByTagName("p");
8 document.write("The innerHTML of the second paragraph is: " + x[2].innerHTML);
9 </script>
10
11 </body>
?注意:下标号从 0 开始。
2.HTML DOM 节点列表长度
length 属性定义节点列表中节点的数量。
您可以使用 length 属性来循环节点列表:
1 x=document.getElementsByTagName("p");
2
3 for (i=0;i<x.length;i++)
4 {
5 document.write(x[i].innerHTML);
6 document.write("<br />");
7 }
导航节点关系
您能够使用三个节点属性:parentNode、firstChild 以及 lastChild ,在文档结构中进行导航。
请看下面的 HTML 片段:
1 <html>
2 <body>
3
4 <p>Hello World!</p>
5 <div>
6 <p>The DOM is very useful!</p>
7 <p>This example demonstrates node relationships.</p>
8 </div>
9
10 </body>
11 </html>
- 首个 <p> 元素是 <body> 元素的首个子元素(firstChild)
- <div> 元素是 <body> 元素的最后一个子元素(lastChild)
- <body> 元素是首个 <p> 元素和 <div> 元素的父节点(parentNode)
firstChild 属性可用于访问元素的文本:
1 <html>
2 <body>
3
4 <p id="intro">Hello World!</p>
5
6 <script>
7 x=document.getElementById("intro");
8 document.write(x.firstChild.nodeValue);
9 </script>
10
11 </body>
12 </html>
DOM 根节点
这里有两个特殊的属性,可以访问全部文档:
- document.documentElement - 全部文档
- document.body - 文档的主体
1 <html>
2 <body>
3
4 <p>Hello World!</p>
5 <div>
6 <p>The DOM is very useful!</p>
7 <p>This example demonstrates the <b>document.body</b> property.</p>
8 </div>
9
10 <script>
11 alert(document.body.innerHTML);
12 </script>
13
14 </body>
15 </html>
childNodes 和 nodeValue
除了 innerHTML 属性,您也可以使用 childNodes 和 nodeValue 属性来获取元素的内容。
下面的代码获取 id="intro" 的 <p> 元素的值:
1 <html>
2 <body>
3
4 <p id="intro">Hello World!</p>
5
6 <script>
7 var txt=document.getElementById("intro").childNodes[0].nodeValue;
8 document.write(txt);
9 </script>
10
11 </body>
12 </html>
getElementById 是一个方法,而 childNodes 和 nodeValue 是属性。
在本教程中,我们将使用 innerHTML 属性。不过,学习上面的方法有助于对 DOM 树结构和导航的理解。