核心導航屬性速查表
| 屬性 | 說明 | 回傳型別 | 含文字節點 |
parentNode | 父節點 | Element | 否 |
parentElement | 父元素(IE9+) | Element | 否 |
childNodes | 所有子節點 | NodeList | 是 |
children | 所有子元素 | HTMLCollection | 否 |
firstChild | 第一個子節點 | Node | 是 |
firstElementChild | 第一個子元素 | Element | 否 |
lastChild | 最後一個子節點 | Node | 是 |
lastElementChild | 最後一個子元素 | Element | 否 |
nextSibling | 下一個同胞節點 | Node | 是 |
nextElementSibling | 下一個同胞元素 | Element | 否 |
previousSibling | 上一個同胞節點 | Node | 是 |
previousElementSibling | 上一個同胞元素 | Element | 否 |
常見陷阱:文字節點干擾
<div id="parent">
<span>Child 1</span>
<span>Child 2</span>
</div>
var parent = document.getElementById('parent');
parent.firstChild; // #text (換行縮排文字節點) ⚠️
parent.firstElementChild; // <span>Child 1</span> ✅
parent.childNodes.length; // 5 (text, span, text, span, text)
parent.children.length; // 2 ✅
實戰工具函數
獲取第 n 個子元素
function getNthChildElement(parent, n) {
var children = parent.children || parent.childNodes;
var count = 0;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType === 1) { // Element
if (count === n) return children[i];
count++;
}
}
return null;
}
// 現代寫法(IE9+)
function getNthChildElementModern(parent, n) {
return parent.children[n] || null;
}
獲取所有同胞元素
function getSiblings(el) {
var siblings = [];
var sibling = el.parentNode.firstChild;
while (sibling) {
if (sibling.nodeType === 1 && sibling !== el) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
}
// 現代寫法
function getSiblingsModern(el) {
return Array.prototype.filter.call(el.parentNode.children, function(child) {
return child !== el;
});
}
查找最近的祖先元素(原生 closest Polyfill)
if (!Element.prototype.closest) {
Element.prototype.closest = function(selector) {
var el = this;
while (el) {
if (el.matches(selector)) return el;
el = el.parentElement;
}
return null;
};
}
// 使用
var container = button.closest('.container');
jQuery 對應方法對照
| 原生 | jQuery | 備註 |
| parentNode | .parent() | |
| parentElement | .parent() | |
| children | .children() | jQuery 只回傳元素 |
| firstElementChild | .children().first() | |
| nextElementSibling | .next() | |
| previousElementSibling | .prev() | |
| querySelectorAll | .find() | 後代 |
| closest | .closest() | 祖先 |
| 同胞元素 | .siblings() | |
選擇器關係速記
$('A B') // A 的所有後代(含非直接)
$('A > B') // A 的直接子元素
$('A + B') // A 緊鄰的下一個同胞
$('A ~ B') // A 之後的所有同胞
總結
- 優先使用
Element 版本屬性(children、firstElementChild 等),避免文字節點干擾
- 現代瀏覽器支援
closest()、matches(),舊環境可用 Polyfill
- jQuery 方法已內部處理文字節點問題,語意更清晰
- 理解原生導航機制,除錯與無庫環境開發更從容