紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS NodeList:forEach 走訪、轉陣列與 live、static 差別

JS NodeList:forEach 走訪、轉陣列與 live、static 差別 特色圖片

NodeList 是節點(node)的集合,通常由 Node.childNodes 這類屬性,或 document.querySelectorAll() 這類方法回傳。它有 length 與用索引存取的元素,看起來像陣列,但不是真正的 Array。

MDN 說明,這個介面原本是想做出「不可修改的清單」,現在是為了不破壞既有程式才繼續支援。這不代表要避開它:你不會自己建立 NodeList,而是從這些沒有被棄用的 API 拿到,只要留意它和真正陣列的語意差異。

NodeList 的成員

NodeList 只有一個屬性與五個方法:

成員說明
length唯讀,清單裡的節點數量
item(index)依索引回傳節點,超出範圍回傳 null
forEach()對每個節點執行一次回呼函式
entries()回傳 iterator,每一筆是 [索引, 節點]
keys()、values()回傳 iterator,分別走訪索引與節點

沒有 map()、filter() 這類陣列方法,需要時要先轉成陣列。取得清單的方式在下一節說明。

取得 NodeList 與基本讀取

範例使用下面的 HTML:

<ul id="parent"><li class="item">A</li><li class="item">B</li></ul>

document.querySelectorAll() 與 childNodes 回傳的都是 NodeList。NodeList 是介面,不能自己用 new 建立:

function errorName(fn) {
  try {
    fn();
    return "no error";
  } catch (e) {
    return e.name;
  }
}

const parent = document.getElementById("parent");
const staticList = document.querySelectorAll(".item");
const liveList = parent.childNodes;

console.log(staticList instanceof NodeList);       // true
console.log(liveList instanceof NodeList);         // true
console.log(Array.isArray(staticList));            // false
console.log(staticList.length);                    // 2
console.log(errorName(() => new NodeList()));      // TypeError

querySelectorAll() 的選擇器與回傳細節,可以看 document.querySelectorAll() 一文,本文只談 NodeList 本身。

length 與 item()

length 是清單的數量,常拿來當 for 迴圈的上限。取得單一節點有兩種寫法:nodeList[index] 或 nodeList.item(index)。MDN 說明在 JavaScript 裡直接用索引就可以;兩者超出範圍時的結果不同,item() 沒有傳參數則丟出 TypeError:

console.log(staticList[0].textContent);          // A
console.log(staticList.item(1).textContent);     // B
console.log(String(staticList[5]));              // undefined
console.log(staticList.item(5));                 // null
console.log(errorName(() => staticList.item())); // TypeError

MDN 補充,item() 主要是為了非 JavaScript 的 DOM 實作而存在,在 JavaScript 裡通常用索引即可。

走訪 NodeList

MDN 說明 NodeList 雖然不是 Array,仍可以用 forEach() 走訪,也可以用 for 迴圈與 for...of:

const loopTexts = [];
for (let i = 0; i < staticList.length; i++) {
  loopTexts.push(staticList[i].textContent);
}

const ofTexts = [];
for (const li of staticList) {
  ofTexts.push(li.textContent);
}

console.log(loopTexts.join());     // A,B
console.log(ofTexts.join());       // A,B

forEach()

forEach(callback, thisArg) 的回呼函式接收三個參數:目前的節點、索引、整個 NodeList。第二個參數 thisArg 可指定回呼函式裡的 this,回傳值是 undefined:

const eachTexts = [];
staticList.forEach((li, index, list) => {
  eachTexts.push(`${index}:${li.textContent}:${list.length}`);
});

console.log(eachTexts.join());     // 0:A:2,1:B:2

const prefixed = [];
staticList.forEach(function (li) {
  prefixed.push(this.prefix + li.textContent);
}, { prefix: "#" });

console.log(prefixed.join());      // #A,#B

entries()、keys()、values()

三個方法回傳的都是 iterator(樂詞網電子計算機名詞譯為「疊代器」):keys() 的鍵是從 0 開始的整數,values() 的值是節點,entries() 兩者成對:

console.log(Array.from(staticList.keys()).join());                                 // 0,1
console.log(Array.from(staticList.values(), (li) => li.textContent).join());      // A,B
console.log(Array.from(staticList.entries(), ([i, li]) => i + "=" + li.textContent).join());   // 0=A,1=B

不要用 for…in

MDN 明確提醒:不要用 for...in 列舉 NodeList。它會連 length、item 這些屬性也列出來,假設裡面只有元素的程式會出錯;而且 for...in 不保證任何特定的順序:

const keys = [];
for (const key in staticList) {
  keys.push(key);
}

console.log(keys.includes("length"), keys.includes("item"));   // true true

轉成陣列

NodeList 沒有 map()、filter() 這類陣列方法。MDN 說明可以用 Array.from() 轉成真正的陣列;展開運算子(...)也能做到同樣的事,因為 NodeList 可以迭代:

console.log(typeof staticList.map);                                    // undefined

const nodes = Array.from(staticList);

console.log(Array.isArray(nodes));                                     // true
console.log(nodes.map((li) => li.textContent).join());                 // A,B
console.log([...staticList].filter((li) => li.textContent !== "A").length);   // 1
console.log(Array.from(staticList, (li) => li.textContent.toLowerCase()).join());   // a,b

Array.from() 的第二個參數可以直接放轉換函式,一步完成轉換與 map()。

即時(live)與靜態(static)

MDN 說明,NodeList 有兩種:

  • 即時(live,樂詞網電子計算機名詞譯為「活」):大多數 NodeList 都是,DOM 的變動會自動更新這份集合。例如 Node.childNodes。
  • 靜態(static):DOM 的變動不影響集合的內容。MDN 說明,document.querySelectorAll() 是唯一回傳靜態 NodeList 的 API。

MDN 提醒,挑選走訪方式、決定要不要快取 length 時,要記得這個差別。用同一份 HTML 比較:

const before = liveList.length;

const added = document.createElement("li");
added.className = "item";
parent.appendChild(added);

console.log(before, liveList.length, staticList.length);        // 2 3 2
console.log(document.querySelectorAll(".item").length);         // 3

加入第三個 li 之後,liveList 自動變成 3 個,之前取得的 staticList 仍是 2 個;重新執行 querySelectorAll() 才會拿到新的結果。

走訪即時清單時移除節點

即時清單在迴圈中移除節點時,後面的節點會往前補位,索引就會跳過節點。靜態清單沒有這個問題:

<ul id="parent2"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
const parent2 = document.getElementById("parent2");
const live2 = parent2.childNodes;

for (let i = 0; i < live2.length; i++) {
  parent2.removeChild(live2[i]);
}

console.log(parent2.childNodes.length);        // 2

const fixed = document.querySelectorAll("#parent2 li");

fixed.forEach((li) => parent2.removeChild(li));

console.log(parent2.childNodes.length);        // 0

第一個迴圈移除 4 個子節點裡的第 1、第 3 個就結束了:移除之後清單變短、後面的節點補位,i 繼續增加,就跳過了補位的節點。要清空時,用靜態清單,或每次都移除第一個節點。

NodeList 與 HTMLCollection

MDN 的 NodeList.length 範例用的是 document.getElementsByTagName(),但依 MDN 說明,這個方法回傳的是 HTMLCollection,不是 NodeList:

console.log(document.getElementsByTagName("li") instanceof NodeList);          // false
console.log(document.getElementsByTagName("li") instanceof HTMLCollection);    // true

兩者都有 length 與索引存取,但是不同的介面,本文只談 NodeList。

注意事項

  1. 不是陣列:沒有 map()、filter(),要先用 Array.from() 或 [...nodeList] 轉成陣列。
  2. 不要用 for...in:會列出 length、item 等屬性,改用 for...of、forEach() 或一般 for。
  3. 要分清楚即時或靜態:childNodes 是即時的,querySelectorAll() 是靜態的。
  4. 即時清單別邊走訪邊移除:用靜態清單,或每次移除第一個節點。
  5. 索引超出範圍:nodeList[i] 是 undefined,item(i) 是 null。
  6. 不能 new NodeList():沒有對外的建構子。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data,查詢日期 2026-11-24):NodeList 與 length、item() 從 Chrome 1、Firefox 1、Safari 1 開始支援。

forEach()、entries()、keys()、values() 從 Chrome 51、Firefox 50、Safari 10 開始支援。BCD 沒有 Node.js 與 Deno 的支援紀錄。

補充說明:範例在 Chrome 158 執行;Node.js 沒有 DOM,typeof NodeList 是 undefined。MDN 的範例是 forEach() 的 thisArg、for...of 與即時、靜態的說明,其餘是本文自己的示範。

參考資料與延伸閱讀

發佈留言