標準瀏覽器有 nextElementSibling、previousElementSibling、firstElementChild、lastElementChild、children 這一整組元素導航屬性,等於內建的 TreeWalker。但在需要支援舊版 IE 的年代,這些都不存在。Firefox 官網上流傳的一組小函數,正好能補上這個缺口。
問題不在於找不到兄弟節點,而在於原始碼為了排版而產生的空白文字節點與註解節點。這組函數的做法是先定義什麼叫「可忽略」,之後所有導航都繞過它們。
function is_all_ws(nod) {
return !(/[^\t\n\r ]/.test(nod.data));
}
function is_ignorable(nod) {
return (nod.nodeType == 8) || ((nod.nodeType == 3) && is_all_ws(nod));
}
nodeType == 8 是註解節點,nodeType == 3 是文字節點;只有「純粹由 tab、換行、空白組成」的文字節點才會被略過,真正的內容文字會被保留。
function node_before(sib) {
while ((sib = sib.previousSibling)) {
if (!is_ignorable(sib)) return sib;
}
return null;
}
function node_after(sib) {
while ((sib = sib.nextSibling)) {
if (!is_ignorable(sib)) return sib;
}
return null;
}
function first_child(par) {
var res = par.firstChild;
while (res) {
if (!is_ignorable(res)) return res;
res = res.nextSibling;
}
return null;
}
function last_child(par) {
var res = par.lastChild;
while (res) {
if (!is_ignorable(res)) return res;
res = res.previousSibling;
}
return null;
}
四個函數的結構完全一致:從起點出發,朝單一方向前進,遇到第一個「不可忽略」的節點就回傳,走到盡頭則回傳 null。這種「條件過濾 + 單向掃描」的模式,比一次寫出五個專用屬性更容易維護,也更容易擴充——想多排除某類節點,只要改 is_ignorable 一處即可。
今天的專案幾乎不必再手寫這些程式了,原生 API 與各家框架都已提供完善的替代方案。但理解它的思路仍有價值:它示範了如何用極小的程式碼代價,在能力不齊全的環境中補出一層一致的介面。