childNodes 與 children 都是獲取子節點集合,但包含節點類型不同,導致遍歷結果差異巨大。
| 屬性 | 包含節點類型 | 返回集合類型 | 標準 |
|---|---|---|---|
| childNodes | 所有:Element、Text、Comment 等 | NodeList (即時) | W3C DOM |
| children | 僅 Element(元素節點) | HTMLCollection (即時) | DOM Level 3 / 事實標準 |
<div id="div1">
<span id="s1"></span>
</div>
<script>
const div = document.getElementById('div1');
console.log('children:', [...div.children].map(e => e.tagName));
// ["SPAN"] —— 僅元素
console.log('childNodes:', [...div.childNodes].map(n => n.nodeName));
// ["#text", "SPAN", "#text"] —— 含換行文本節點!
</script>
<div id="div1">
<span id="s1"></span>
</div>
// ↑ 換行和縮進產生 #text 節點
<div id="div1"><span id="s1"></span></div>
// ↑ 無空白,childNodes === children
// ✅ 推薦:只遍歷元素
for (const child of element.children) { ... }
element.firstElementChild;
element.lastElementChild;
element.previousElementSibling;
element.nextElementSibling;
// ⚠️ 避免:childNodes 需手動過濾 nodeType === 1
for (const node of element.childNodes) {
if (node.nodeType === 1) { ... }
}
| 含文本/註釋 | 僅元素 | 說明 |
|---|---|---|
| firstChild | firstElementChild | 首個子節點 |
| lastChild | lastElementChild | 末個子節點 |
| previousSibling | previousElementSibling | 前一個兄弟 |
| nextSibling | nextElementSibling | 後一個兄弟 |
| parentNode | parentElement | 父節點 (parentElement 可能為 null) |
children 系列 API 專為元素節點設計,符合 99% 遍歷需求,無需手動過濾文本節點。現代開發默認使用 children/firstElementChild 等 ElementTraversal API,代碼更簡潔、語義更清晰、性能略優。