我设置了一些简单的 HTML 和 JS 代码,以便更好地处理遍历 DOM。
这是我的 HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sandbox</title>
</head>
<body>
<div>
<h1 id="title">Sandbox</h1>
<button id="clickMe" onclick="playingAroundWithNodes()">Play with nodes!</button>
</div>
</body>
<script type="text/javascript" src="Sandbox3.js"></script>
</html>
这是我的 JavaScript:
function playingAroundWithNodes() {
//Getting a reference to some nodes!
var theHtmlNode = document.childNodes[1];
var theHeadNode = theHtmlNode.childNodes[0];
var theBodyNode = theHtmlNode.childNodes[1];
//Let's check out those nodes!
console.log("theHtmlNode is a " + theHtmlNode.nodeName + " type node.");
console.log("theHeadNode is a " + theHeadNode.nodeName + " type node.");
console.log("theBodyNode is a " + theBodyNode.nodeName + " type node.");
}
这是我得到的控制台日志:
theHtmlNode is a HTML type node.
theHeadNode is a HEAD type node.
theBodyNode is a #text type node.
什么给了?那个文本节点到底在哪里,不是标题节点吧?我很困惑,并且已经玩了很多次(发现 body 节点实际上是根据 js 的 HEAD 的第三个子节点,但查看 HTML 对我来说没有意义)。我可以看到它是第三个后代或其他什么,但我认为 child 意味着直系 child ......任何帮助表示感谢!
最佳答案
首先,你对我有新的想法。我没有意识到document
有一个childNodes
根本没有属性(通常通过 document.documentElement
访问根元素(html))。
对于文本节点,这些发生取决于您如何格式化 HTML 文件。上面出现的文本节点可能是一个返回字符或结束 </head>
之间的几个空格。并开放<body>
.
您可能正在寻找的是(最初是非标准的,但现在最近proposed for standardisation)element.children
。 John Resig has a good overview .
因此,如果您按如下方式修改上面的代码,您将得到您所期望的结果:
var theHeadNode = theHtmlNode.children[0];
var theBodyNode = theHtmlNode.children[1];
关于javascript - 意外的 childNodes 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941157/