children 返回**元素節點**集合(僅 Element),childNodes 包含文本/註釋節點。firstChild/lastChild 返回首尾**所有類型**子節點,firstElementChild/lastElementChild 才只返回元素。
<div id="test">
<a></a>
<table></table>
</div>
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
children 包含註釋節點,現代瀏覽器已修正。firstChild 常被換行符文本節點佔據,務必用 firstElementChild(IE9+)。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);
}