HTML DOM之三:节点关系导航

 

1、获取节点列表

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <p>Hello World!</p>
 6 <p>DOM 很有用!</p>
 7 <p>本例演示 <b>length</b> 属性。</p>
 8 
 9 <script>
10 x=document.getElementsByTagName("p");
11 for (i=0;i<x.length;i++)
12   { 
13   document.write(x[i].innerHTML);
14   document.write("<br>");
15   }
16 </script>
17 </body>
18 </html>
复制代码

 

2、导航节点关系

您能够使用三个节点属性:parentNode、firstChild 以及 lastChild、childNodes[],在文档结构中进行导航。

请看下面的 HTML 片段:

<html>
<body>

<p>Hello World!</p>
<div>
  <p>DOM 很有用!</p>
  <p>本例演示节点关系。</p>
</div>

</body>
</html>
  • 首个 <p> 元素是 <body> 元素的首个子元素(firstChild)
  • <div> 元素是 <body> 元素的最后一个子元素(lastChild)
  • <body> 元素是首个 <p> 元素和 <div> 元素的父节点(parentNode)

例子2.1:firstChild 属性可用于访问元素的文本:

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <p id="intro">Hello World!</p>
 6 
 7 <script>
 8 x=document.getElementById("intro");
 9 document.write(x.firstChild.nodeValue);
10 </script>
11 
12 </body>
13 </html>
复制代码

 

例子2.2:除了 innerHTML 属性,您也可以使用 childNodes 和 nodeValue 属性来获取元素的内容。

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <p id="intro">Hello World!</p>
 6 
 7 <script>
 8 txt=document.getElementById("intro").childNodes[0].nodeValue;
 9 document.write(txt);
10 </script>
11 
12 </body>
13 </html>
复制代码

 

3、DOM 根节点

这里有两个特殊的属性,可以访问全部文档:

  • document.documentElement - 全部文档
  • document.body - 文档的主体
复制代码
 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <p>Hello World!</p>
 6 <div>
 7 <p>DOM 很有用!</p>
 8 <p>本例演示 <b>document.body</b> 属性。</p>
 9 </div>
10 
11 <script>
12 alert(document.body.innerHTML);
13 </script>
14 
15 </body>
16 </html>
复制代码

 

 

posted on   gogoy  阅读(296)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示