javascript - 意外的 childNodes 行为

标签 javascript html dom dom-traversal textnode

我设置了一些简单的 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.childrenJohn Resig has a good overview .

因此,如果您按如下方式修改上面的代码,您将得到您所期望的结果:

var theHeadNode = theHtmlNode.children[0];
var theBodyNode = theHtmlNode.children[1];

关于javascript - 意外的 childNodes 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941157/

相关文章:

javascript - 如何创建和使用动态分层 JSON?

javascript - Cheerio 中的 DOM 选择器不起作用

javascript - CSS:使子div宽度自动适应其中的内容,而不是完整的父宽度

javascript - 停止 div 背景的流式传输

javascript - 以编程方式设置for循环的第三条语句

html - 为什么我的图像没有内联显示

javascript - Safari 点击 != 关注单选按钮

html - 当窗口宽度变小时图像从容器中出来

c++ - 如何在QtWebKit中访问网页的DOM?

xml - 检查XML DOM XMLDOC时出错