当前位置: 代码迷 >> JavaScript >> 为什么我不能从body标签访问子节点?
  详细解决方案

为什么我不能从body标签访问子节点?

热度:106   发布时间:2023-06-07 13:50:44.0

而且我无法通过[9],[11]访问身体孩子的div标签

我之前使用bd.firstChild,bd.childNodes [n],但始终显示null

 <html> <head> <meta charset="EUC-KR"> <title>Insert title here</title> <script> var rt = document.getRootNode(); document.write(rt.nodeName + " "); //document var ht = rt.firstChild; document.write(ht.nodeName + " "); // html var hd = ht.firstChild; document.write(hd.nodeName + " "); // head var bd = hd.nextSibling; document.write(bd.nodeName + " "); // body </script> </head> <body> <br/><br/><br/><br/><br/><br/> <h1>1</h1> <h2>2</h2> </body> </html> 

在文档完成之前将代码片段编辑为document.write之前,我创建了以下代码-在文档完成之后,许多人不使用document.write,但是在渲染标签/节点之前无法显示它们:

仅仅获得节点似乎有一些奇怪的事情-Chrome在身体之后的头部之后添加了换行符

这显示了这个问题

您想查看

 <!doctype html> <html> <head> <title></title> </head> <body> <p></p> <script> // https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter/acceptNode // https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker var nodeIterator = document.createNodeIterator( // Node to use as root document.querySelector('html'), // Only consider nodes that are text nodes (nodeType 3) NodeFilter.SHOW_ELEMENT, // Object containing the function to use for the acceptNode method // of the NodeFilter { acceptNode: function(node) { // Logic to determine whether to accept, reject or skip node // In this case, only accept nodes that have content // other than whitespace if (!/^\\s*$/.test(node.data)) { return NodeFilter.FILTER_ACCEPT; } } }, false ); // Show the content of every non-empty text node that is a child of root var node; while ((node = nodeIterator.nextNode())) { console.log(node.tagName); } /* ----------- Older code ------------- */ /* var rt = document.getRootNode(); console.log("Root", rt.nodeName + " "); //document var ht = rt.firstChild; console.log("Root's firstChild", ht.nodeName + " "); // html var HTML = ht.nextSibling; console.log("html's nextSibling", HTML.nodeName + " "); // HTML var HEAD = HTML.firstChild; console.log("Html's firstChild", HEAD.nodeName + " "); // HEAD var newLine = HEAD.nextSibling; var BODY = newLine.nextSibling; console.log("newLine's nextSibling", BODY.nodeName + " "); // BODY */ </script> </body> </html> 

  • 每当遇到<script>元素时,浏览器的网页解析器(和文档生成器)都会暂停(假设它没有asyncdefer属性)。
  • document.write导致参数文本在调用时立即添加到文档流中。
    • 参数文本将附加到当前解析的文档文本中,然后同步输入到文档构建器中。
      • 这种同步行为以及解析文本和从文本中创建文档节点的事实非常昂贵,这就是为什么不赞成document.write并且不鼓励使用它的原因。
  • 您要将人类可读的文本传递到document.write因此新的#text节点将立即添加到<script>元素所在的位置,该元素位于<head>元素内。
  • 但是所有这些都不相关,因为在您的情况下, <html>firstChild实际上是一个由<html><head>之间的空格组成的#text节点,唯一的消除方法是使用<html><head>而不是<html>(#text "\\r\\n\\r\\n")<head>
  • var bd不是<body>元素。 使用调试器。
  • 另外,避免使用基于node的DOM API,因为它包含诸如空格#text节点和注释之类的内容。 通常最好改用基于Element的DOM API。
  相关解决方案