问题描述
而且我无法通过[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>
1楼
在文档完成之前将代码片段编辑为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>
2楼
-
每当遇到
<script>
元素时,浏览器的网页解析器(和文档生成器)都会暂停(假设它没有async
或defer
属性)。 -
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。