javascript - 文本是否也被视为 DOM 中的节点?

标签 javascript html dom

我开始阅读有关 JavaScript 和 DOM 的内容,然后我找到了 as on this site在这样的结构中:

<html>
  <head>
    <title>The title</title>
  </head>
  <body>
     The body
   </body>
</html>

文本 The titleThe body 也被视为节点,如下图所示(来自同一站点):

DOM representation

请注意,标题主体 表示为实际标题各自正文节点的子节点。让我感到困惑的是:标题正文 文本不只是节点的值 <title><body>

我在http://www.w3schools.com/js/js_htmldom_navigation.asp上遇到过类似的例子在这样的结构中:

<html>
  <head>
      <title>DOM Tutorial</title>
  </head>
  <body>
      <h1>DOM Lesson one</h1>
      <p>Hello world!</p>
  </body> 
</html>

<h1> 的值和 <p>元素也像节点一样被描述:

<h1> has one child: "DOM Lesson one"

<p> has one child: "Hello world!"

为什么节点内的文本值被视为不同的节点,而不仅仅是包含它们的节点的文本值?

谢谢!

最佳答案

What confuses me is: aren't The title and The body text just values of the nodes and ?

不,它们实际上是那些节点的子节点。您可以通过输出 title 标签的 children 属性来查看它:

document.querySelector('title').children

文本节点表示为 Node.TEXT_NODE=3 如前所述 here .只有表单 DOM 元素(如输入)具有 value 属性,并且在这些输入中输入的文本包含在那里。

除了文本节点,还有注释节点,像这样:

<title><!-- DOM Tutorial --></title>

Why are text values inside nodes considered different nodes and not just text values of the nodes which contain them?

可能是因为它们需要在内存中表示不同的结构,以便可以对其进行操作,例如,更改文本的颜色。

关于javascript - 文本是否也被视为 DOM 中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524906/

相关文章:

javascript - 如何将图像转换为文件中的 Base64 字符串?

javascript - webpack 4 react jsx 无法渲染图像

javascript - Selenium-Java-geckodriver : Test Execution halts with JavaScript error as "document.getElementById(...) is null"

php - 错误 : Unknown column 'joinedactivities.searchact id = searchact.id' in 'on clause'

javascript - 如何使用 Javascript 替换 DOM 元素?

javascript - 使用 jQuery 和 javascript 附加元素时出现奇怪的格式

javascript - 无法让 Discord.js 机器人响应消息内容,只能使用 <@null>

javascript - 如何设置js为背景?

html - 卡片翻转在 IE10 中无法正常工作

javascript - 确定单击元素时调用的 Javascript 函数