[英]JavaScript DOM traversal order
我編寫了以下頁面來演示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>
據我說,輸出應該是body-> div-> p,但它是body-> #text。 有人可以解釋什么是#text,為什么我沒有得到想要的命令?
這些是“空文本”節點,我在這里在博客中發布了這些內容:
https://weblogs.asp.net/stevewellens/secret-covert-hush-hush-white-space-in-the-dom-exposed
此處對它們進行了說明: http : //www.w3.org/DOM/faq.html#emptytext
body
和div
之間有一個空格:
<body>
<div>
該空格盡管在概念上是空的,但它是DOM的一部分,並且是DOM的一部分。 在此遍歷中,它被解釋為#text
。 (您可能會看到很多 #text
節點。)
您可能應該嘗試訪問firstElementChild ,它會忽略類型不等於1的節點,例如文本元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.