document.querySelector / document.querySelectorAll 取得的 NodeList 是靜態的

HTMLCollection / NodeList 在大部分情況下是即時更新,但透過 document.querySelector / document.querySelectorAll 取得的 NodeList 是靜態。

這是什麼意思?

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<button onclick="addItem()">Add Item</button>

<p id="liveCollection"></p>
<p id="staticCollection"></p>

這裡我們有一個 ul 清單和一個按鈕,用於向清單中添加新的項目。接著是 JavaScript 程式:

// 取得即時更新的 HTMLCollection
let liveItems = document.getElementsByTagName("li");

// 取得靜態的 NodeList
let staticItems = document.querySelectorAll("li");

function addItem() {
  // 向清單中添加新的項目
  let newItem = document.createElement("li");
  newItem.textContent = "New Item";
  document.getElementById("myList").appendChild(newItem);
  
  // 顯示集合的長度
  document.getElementById("liveCollection").innerHTML = 
    "HTMLCollection (Live): " + liveItems.length;
  
  document.getElementById("staticCollection").innerHTML = 
    "NodeList (Static): " + staticItems.length;
}

行為解釋:

getElementsByTagName(“li”) 返回的 liveItems 是一個即時更新的 HTMLCollection:

  1. 每次按下按鈕並新增項目時,liveItems 都會立即反映 DOM 的變化。因此 liveItems.length 會隨著新的 元素加入而自動更新。
    querySelectorAll(“li”) 返回的 staticItems 是靜態的 NodeList:

2. 當按下按鈕新增項目後,staticItems 不會更新,它的長度會保持在初始選取時的數量,即使 DOM 中新增了項目,staticItems.length 不會變化。

結果:

當你按下按鈕後,畫面上的顯示將會像這樣:

  • HTMLCollection (Live): 4
  • NodeList (Static): 3

即時更新的 HTMLCollection 會自動增加元素數量,而靜態的 NodeList 不會改變。

總結:

  • HTMLCollection(以及某些 NodeList)是動態的,它們會即時反映 DOM 的變化。
  • querySelectorAll 取得的 NodeList 是靜態的,不會隨 DOM 更新而改變。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *