萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

DOM children 集合與 firstChild/lastChild 節點遍歷詳解

children 返回**元素節點**集合(僅 Element),childNodes 包含文本/註釋節點。firstChild/lastChild 返回首尾**所有類型**子節點,firstElementChild/lastElementChild 才只返回元素。

結構示例

<div id="test">
  <a></a>
  <table></table>
</div>

API 對比


test.children[0].tagName;        // "A"       ← 推薦
test.children[1].tagName;        // "TABLE"
test.firstChild.nodeName;        // "#text"   ← 換行文本節點!
test.firstElementChild.tagName;  // "A"       ← 現代標準
test.lastChild.nodeName;         // "#text"
test.lastElementChild.tagName;   // "TABLE"

表格遍歷實戰


const tbl = document.getElementById('tbl');
const tbody = tbl.tBodies[0] || tbl.firstElementChild; // 兼容無 tbody

// 方式一:rows 集合(最語義化)
for(const row of tbody.rows){
    console.log(row.cells[0].innerText);
}

// 方式二:children + 索引
for(let i=0; i

避坑指南

  • 舊 IE children 包含註釋節點,現代瀏覽器已修正。
  • firstChild 常被換行符文本節點佔據,務必用 firstElementChild(IE9+)。
  • 需支援 IE8 時,封裝 firstElementChild || firstChild 並過濾 nodeType===1。

現代遍歷推薦


// 元素子節點迭代器
for(const child of element.children){ ... }

// 遞歸深度優先
function walk(el, fn){
    fn(el);
    for(const child of el.children) walk(child, fn);
}
copyright © 萬盛學電腦網 all rights reserved