JavaScript DOM遍历顺序

时间:2014-06-03 14:19:36

标签: javascript

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

<html>
<head>
<title>DOM Traversal</title>
</head>

<body>

<div>
<p>Sample paragraph</p>
</div>
<h1>Sample H1</h1>

<script>

// Traversing the DOM tree
"use strict";
var node = document.body;

document.addEventListener("DOMContentLoaded", function (event) {
    while(node) {
        console.log(node);
        node = node.firstChild;
    }
}, false);

</script>
</body>

</html>

根据我的说法,输出应该是正文 - &gt; div - &gt; p但它是身体 - &gt; #文本。有人可以解释什么是#text以及为什么我没有得到所需的订单?

3 个答案:

答案 0 :(得分:2)

那些是&#34;空文&#34;节点,我在这里写了博客:

https://weblogs.asp.net/stevewellens/secret-covert-hush-hush-white-space-in-the-dom-exposed

这里解释了它们:http://www.w3.org/DOM/faq.html#emptytext

答案 1 :(得分:1)

bodydiv之间有空格:

<body>

<div>

这个空白虽然在概念上是空的,但却存在并且是DOM的一部分。在此遍历中,它被解释为#text。 (您可能会看到很多#text个节点。)

答案 2 :(得分:1)

您应该尝试访问firstElementChild,它会忽略没有type等于1的节点,例如文本元素。


相关问题