Javascript 解释这个DOM遍历顺序

Javascript 解释这个DOM遍历顺序,javascript,Javascript,我编写了以下页面作为DOM遍历演示: <html> <head> <title>DOM Traversal</title> </head> <body> <h1>Sample H1</h1> <div id="text"> <p>Sample paragraph</p>

我编写了以下页面作为DOM遍历演示:

<html>
    <head>
        <title>DOM Traversal</title>
    </head>
    <body>
        <h1>Sample H1</h1>
        <div id="text">
            <p>Sample paragraph</p>
        </div>
    </body>
    <script>
        // Traversing the DOM tree
        "use strict";

        var node = document.body;

        while(node) {
            console.log(node);
            node = node.lastChild;
        }
    </script>
</html>

DOM遍历
样本H1
示例段落

//遍历DOM树 “严格使用”; var节点=document.body; while(节点){ console.log(节点); node=node.lastChild; }

令人惊讶的是,我得到的输出是
body
标记,后跟
script
标记。这怎么可能?
脚本
标记不是
主体
标记的兄弟吗?另外,为什么没有遍历
body
的子节点?

您不能将
脚本
元素添加到
body
元素之外。浏览器会自动更正HTML,将
脚本
移动到
正文
的末尾,从而解释您得到的结果


html
元素只能包含
head
body
元素作为其子元素。其他任何内容都必须放在这两个元素中。

除了iMoses所说的之外,您的脚本块将在解析整个文档之前运行,因为它不会等待domReady事件。这似乎导致了一种竞赛状态

如果您将脚本留在原处,但等待domReady,则会得到稍微不同的结果(尽管仍然不是您想要的结果)

编辑:将脚本改为输出“node.outerHTML”,您将看到脚本块被移动或复制到正文中。 不必等待文档准备就绪,在脚本运行时,您将得到两个脚本块—一个是您的原始脚本块,另一个位于正文末尾,正如iMoses所指出的。
等待文档准备就绪后,您会发现只有(移动的)主体内的文档仍然存在。

解决此类“问题”的一个好方法是首先验证源代码

W3C HTML验证程序等工具将帮助您避免此类问题:

验证代码将返回以下结果:

Line 11, Column 12: document type does not allow element "SCRIPT" here
<script>


The element named above was found in a context where it is not allowed. This could mean that you have incorrectly nested elements -- such as a "style" element in the "body" section instead of inside "head" -- or two elements that overlap (which is not allowed).

One common cause for this error is the use of XHTML syntax in HTML documents. Due to HTML's rules of implicitly closed elements, this error can create cascading effects. For instance, using XHTML's "self-closing" tags for "meta" and "link" in the "head" section of a HTML document may cause the parser to infer the end of the "head" section and the beginning of the "body" section (where "link" and "meta" are not allowed; hence the reported error).
第11行第12列:文档类型此处不允许元素“SCRIPT”
在不允许的上下文中找到了上面命名的元素。这可能意味着您有不正确的嵌套元素,例如“body”部分中的“style”元素而不是“head”内部的元素,或者两个元素重叠(这是不允许的)。
此错误的一个常见原因是在HTML文档中使用XHTML语法。由于HTML的隐式封闭元素规则,此错误可能会产生级联效果。例如,在HTML文档的“head”部分中使用XHTML的“self-closing”标记表示“meta”和“link”,可能会导致解析器推断“head”部分的结尾和“body”部分的开头(其中不允许使用“link”和“meta”;因此报告了错误)。

脚本应该在正文中。也许您的浏览器正在为您更正非标准标记@isherwood:或在
中…右侧。我的意思是,而不是在它之后。只是在几个浏览器中测试了你的代码。似乎它们中的大多数将脚本显示为body的兄弟姐妹和它的子脚本(它显示了两次,内容相同)。而且在所有的模块上,它也会遍历孩子们(请阅读Uweb的答案,看看为什么不适合你)注意到第二个模块,但是只有一个模块(身体内部的模块)运行代码。谢谢你的答案。请在这里查看我的更新代码。我现在应该得到body->div->p,但是我得到body->#文本(如果你能在你的终端运行这个,那就太好了)。什么是错误的?文本也是一个节点,这意味着元素之间的空白实际上是文本节点。这就是你得到的。