在 IE 裡有 previousElementSibling/nextElementSibling 這類「只看元素、跳過空白文字節點」的屬性可用,但在早期 Firefox 上沒有。若又需要「跳過所有不同型別的節點,只找同類型的鄰居」,就得自己遞迴。
// 相容 Firefox:取得同一節點的相同型別上一個相鄰節點
function perviousSiblingSameType(node, cnode) {
// 已經沒有前 siblings,直接回 null
if (node.previousSibling == null) {
return null;
} else {
// 型別不同就繼續往前遞迴
if (node.previousSibling.nodeType != cnode.nodeType) {
return perviousSiblingSameType(node.previousSibling, cnode);
}
// 型別相同,回傳
else if (cnode.nodeType == node.previousSibling.nodeType) {
return node.previousSibling;
}
}
}
// 相容 Firefox:取得同一節點的相同型別下一個相鄰節點
function nextSiblingSameType(node, cnode) {
if (node.nextSibling == null) {
return null;
} else {
if (node.nextSibling.nodeType != cnode.nodeType) {
return nextSiblingSameType(node.nextSibling, cnode);
}
else if (cnode.nodeType == node.nextSibling.nodeType) {
return node.nextSibling;
}
}
}
第二個參數 cnode 是「型別樣板」——通常傳入節點本身即可,因為函式只比對 nodeType 這個數字:
var el = document.getElementById('target');
var prev = perviousSiblingSameType(el, el); // 往前找同為 ELEMENT_NODE 的兄弟
var next = nextSiblingSameType(el, el); // 往後找
型別是數字,不是標籤名。 nodeType 只區分「元素(1)/文字(3)/註解(8)」這類大類,不會分辨是 <div> 還是 <span>。若你要找的其實是「同標籤名的兄弟」,判斷條件應該改成 nodeName:
function nextSameTag(el) {
var n = el.nextElementSibling; // 現代瀏覽器直接有這個屬性
while (n && n.nodeName !== el.nodeName) {
n = n.nextElementSibling;
}
return n;
}
今天不需要這段程式碼了。 nextElementSibling 與 previousElementSibling 已是所有主流瀏覽器的標準(IE9 起支援),本身就是「跳過非元素節點」的語意;若要按條件篩選,Array.prototype.filter.call(el.parentNode.children, ...) 或 :scope 選擇器都比手寫遞迴清楚。這份實作的價值在於示範一個通用思路:當 API 不夠用時,沿著 sibling 鏈一格格走,用遞迴或迴圈持續檢查條件直到命中或走到盡頭。