解释这个DOM遍历顺序

时间:2014-06-03 13:11:53

标签: javascript

我将以下页面编写为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>

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

3 个答案:

答案 0 :(得分:5)

您无法在scripthead元素之外添加body元素。浏览器会自动更正您的HTML,将script移到body的末尾,这会解释您获得的结果。

html元素可能只包含headbody元素作为其子元素。其他任何东西都必须放在这两个元素中。

答案 1 :(得分:4)

除了iMoses所说的,你的脚本块将在解析整个文档之前运行,因为它不会等待domReady事件。这似乎导致了竞争条件。

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

编辑:改变你的脚本改为输出“node.outerHTML”,你会发现脚本块被移动或者被复制到正文中。 在没有等待文档就绪的情况下,在脚本运行时你最终会得到两个脚本块 - 一个是你的原始文件,另一个是在iMoses指出的身体末端。 等待文件准备就绪,你会发现身体内只有(移动的)一个。

答案 2 :(得分:2)

开始解决此类问题的好地方&#39;是先验证来源。

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

http://validator.w3.org/check

验证您的代码将返回以下内容:

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).
相关问题