HTML DOM 子节点

标签 html dom

我正在研究 HTML DOM,我注意到两个属性没有明显的原因彼此不一致。考虑这个简单的 HTML 文件:

<html>
<head>
<title>DOM Example</title>
</head>
<body>
<p>Hello World!</p>
<p>Isn't this exciting?</p>
<p>You're learning to use the DOM!</p>
</body>
<script type="text/javascript" src="script.js"></script>
</html>

我希望 bodyalt_body 相同,但是 .childNodes 坚持给我一个文本节点。 (下面是script.js的内容)

body = document.documentElement.childNodes[1]
alt_body = document.documentElement.lastChild;  
console.log(body.nodeType) //prints 3 (Node.TEXT_NODE)
console.log(alt_body.nodeType) //prints 1 (Node.ELEMENT_NODE)
console.log(body.childNodes.length) //prints 0
console.log(alt_body.childNodes.length) //prints 8

有谁知道为什么会这样?

最佳答案

是因为childNodes也返回一个文本行节点

<html>
    <head>
        <title>DOM Example</title>
    </head>
    <body>
        <p>Hello World!</p>
        <p>Isn't this exciting?</p>
        <p>You're learning to use the DOM!</p>
    </body>
    <script type="text/javascript" src="script.js"></script>
</html>

  1. 0 :将是 <head>节点
  2. 1:将是 empty text (视为一个节点)
  3. 2:将是 <body>节点(此 HTML 中的 lastChild)

像下面这样去掉所有换行符和空格后尝试。

<html><head><title>DOM Example</title></head><body><p>Hello World!</p><p>Isn't this exciting?</p><p>You're learning to use the DOM!</p></body><script type="text/javascript" src="script.js"></script></html>

那么结果就是你所期望的。

关于HTML DOM 子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983525/

相关文章:

javascript - 将输入框转换为组合框以实现 jQuery 自动完成

javascript - 当尝试使用javascript激活一次时,如何防止表单提交按钮的递归激活?

html - 将蒙版应用到 box-shadow

Java 更改和移动非标准的 XML 文件

php - 什么会导致 DOMNode::nodeValue 为空?

javascript - 使用 DOM 节点上的焦点和模糊事件

html - 如何保持 flex box 元素的宽度独立于它的内容

javascript - 点击事件同时打开Popup

javascript - 通过 DOM 中的前置元素无限循环

javascript - 自定义事件的传播