返回課程

nodeType 中有什麼?

重要性:5

腳本顯示什麼?

<html>

<body>
  <script>
    alert(document.body.lastChild.nodeType);
  </script>
</body>

</html>

這裡有個陷阱。

在執行 <script> 時,最後一個 DOM 節點正是 <script>,因為瀏覽器尚未處理頁面的其他部分。

因此結果為 1(元素節點)。

<html>

<body>
  <script>
    alert(document.body.lastChild.nodeType);
  </script>
</body>

</html>