我正在研究 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>
我希望 body
和 alt_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>
- 0 :将是
<head>
节点 - 1:将是
empty text
(视为一个节点) - 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/