萬盛學電腦網

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

JavaScript DOM 節點關係完整指南:父子兄弟遍歷與現代 API 對比

前言

DOM 節點關係操作是前端開發的基礎技能。雖然現代框架(React/Vue/Svelte)抽象了直接 DOM 操作,但理解原生節點關係對於性能優化、第三方庫集成、測試工具開發、遺留代碼維護至關重要。本文系統梳理 Node 接口的關係屬性、遍歷方法、現代 API (Element、ParentNode、ChildNode) 對比,並提供實用工具函數庫。

節點類型與關係屬性速查表

屬性 所屬接口 返回值類型 說明 現代替代
parentNode Node Node | null 父節點 (可能是 Document/DocumentFragment/Element) parentElement (僅 Element)
parentElement Element Element | null 父元素節點 (跳過 Document/Fragment) 推薦使用
childNodes Node NodeList (動態) 所有子節點 (含文本、註釋、CDATA) children (僅元素)
children ParentNode HTMLCollection (動態) 僅子元素節點 (IE9+) 推薦使用
firstChild Node Node | null 第一個子節點 (含文本/註釋) firstElementChild
lastChild Node Node | null 最後一個子節點 lastElementChild
previousSibling Node Node | null 前一個同級節點 (含文本/註釋) previousElementSibling
nextSibling Node Node | null 後一個同級節點 nextElementSibling
previousElementSibling ChildNode Element | null 前一個同級元素 (IE9+) 推薦使用
nextElementSibling ChildNode Element | null 後一個同級元素 推薦使用

關鍵差異:NodeList vs HTMLCollection

// NodeList - 靜態/動態均可,支持 forEach
const nodeList = parent.childNodes;        // 動態
const staticList = parent.querySelectorAll('*'); // 靜態
nodeList.forEach(node => console.log(node.nodeType)); // ✅ 支持

// HTMLCollection - 永遠動態,僅元素,僅數字索引/name/id 訪問
const htmlCollection = parent.children;    // 動態
// htmlCollection.forEach(...) // ❌ 不支持
Array.from(htmlCollection).forEach(el => ...); // ✅ 轉數組

// 陷阱:動態集合長度變化導致循環邏輯錯誤
// ❌ 錯誤
for (let i = 0; i < children.length; i++) {
    children[i].remove(); // length 變化,漏刪
}
// ✅ 正確
while (children.length) children[0].remove();
// 或
Array.from(children).forEach(el => el.remove());

實戰工具函數庫

// dom-relations.ts
export type NodeType = 1 | 3 | 8 | 9 | 11; // ELEMENT, TEXT, COMMENT, DOCUMENT, FRAGMENT

/** 獲取最近的祖先元素 (可選擇器) */
export function closestElement(element: Element, selector: string): Element | null {
    return element.closest(selector);
}

/** 獲取所有祖先元素鏈 (含自身可選) */
export function getAncestors(element: Element, includeSelf = false): Element[] {
    const ancestors = [];
    let current: Element | null = includeSelf ? element : element.parentElement;
    while (current) {
        ancestors.push(current);
        current = current.parentElement;
    }
    return ancestors;
}

/** 獲取所有後代元素 (DFS 順序) */
export function getDescendants(element: Element, tagName?: string): Element[] {
    const walker = document.createTreeWalker(
        element,
        NodeFilter.SHOW_ELEMENT,
        tagName ? { acceptNode: node => node.nodeName.toLowerCase() === tagName.toLowerCase() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP } : undefined
    );
    const descendants = [];
    let node;
    while (node = walker.nextNode()) descendants.push(node);
    return descendants;
}

/** 獲取指定層級的子元素 (直接子元素) */
export function getChildren(element: Element): Element[] {
    return Array.from(element.children);
}

/** 獲取前一個/後一個元素兄弟節點 (跳過文本/註釋) */
export function getPreviousElementSibling(element: Element): Element | null {
    return element.previousElementSibling;
}
export function getNextElementSibling(element: Element): Element | null {
    return element.nextElementSibling;
}

/** 獲取所有同級元素兄弟節點 (含自身可選) */
export function getSiblings(element: Element, includeSelf = false): Element[] {
    const parent = element.parentElement;
    if (!parent) return [];
    const children = Array.from(parent.children);
    return includeSelf ? children : children.filter(el => el !== element);
}

/** 判斷是否為後代 */
export function isDescendant(ancestor: Element, descendant: Element): boolean {
    return ancestor.contains(descendant);
}

/** 獲取兩個元素的最近公共祖先 */
export function getLowestCommonAncestor(a: Element, b: Element): Element | null {
    const ancestorsA = new Set(getAncestors(a, true));
    let current: Element | null = b;
    while (current) {
        if (ancestorsA.has(current)) return current;
        current = current.parentElement;
    }
    return null;
}

/** 獲取元素在父元素中的索引 */
export function getChildIndex(element: Element): number {
    return Array.from(element.parentElement?.children || []).indexOf(element);
}

/** 安全獲取文本內容 (忽略腳本/樣式) */
export function getTextContent(element: Element): string {
    const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, {
        acceptNode: node => {
            const parent = node.parentElement;
            if (parent && ['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(parent.tagName)) {
                return NodeFilter.FILTER_REJECT;
            }
            return NodeFilter.FILTER_ACCEPT;
        }
    });
    let text = '';
    let node;
    while (node = walker.nextNode()) text += node.textContent;
    return text.trim();
}

實戰場景:動態目錄生成

function generateTOC(container: Element, headingSelector = 'h1,h2,h3') {
    const headings = Array.from(container.querySelectorAll(headingSelector));
    const toc = document.createElement('nav');
    toc.className = 'table-of-contents';
    toc.setAttribute('aria-label', '頁面目錄');
    
    const ul = document.createElement('ul');
    let currentLevel = 1;
    let currentUl = ul;
    const stack = [{ level: 1, ul }];
    
    headings.forEach((heading, index) => {
        const level = parseInt(heading.tagName[1]);
        const id = heading.id || `heading-${index}`;
        heading.id = id;
        
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.href = `#${id}`;
        a.textContent = heading.textContent;
        li.appendChild(a);
        
        // 調整層級
        while (level > currentLevel) {
            const newUl = document.createElement('ul');
            stack[stack.length - 1].ul.lastElementChild?.appendChild(newUl);
            stack.push({ level, ul: newUl });
            currentLevel = level;
        }
        while (level < currentLevel) {
            stack.pop();
            currentLevel = stack[stack.length - 1].level;
        }
        stack[stack.length - 1].ul.appendChild(li);
    });
    
    toc.appendChild(ul);
    return toc;
}

現代遍歷 API 對比

API 歸屬接口 返回 瀏覽器支持 推薦指數
element.closest(selector) Element Element | null 全現代瀏覽器 (IE 不支持) ⭐⭐⭐⭐⭐
element.matches(selector) Element boolean 全現代瀏覽器 ⭐⭐⭐⭐⭐
parent.querySelectorAll(selector) ParentNode NodeList (靜態) 全瀏覽器 ⭐⭐⭐⭐
element.getElementsByTagName() Element HTMLCollection (動態) 全瀏覽器 ⭐⭐⭐ (優先 querySelectorAll)
TreeWalker Document Iterator 全瀏覽器 ⭐⭐⭐⭐ (深度遍歷首選)
NodeIterator Document Iterator 全瀏覽器 ⭐⭐⭐ (扁平遍歷)

性能優化建議

  1. 優先使用 children/firstElementChild:避免文本節點干擾,返回 HTMLCollection 雖動態但僅含元素
  2. 靜態查詢用 querySelectorAll:不受後續 DOM 變更影響,支持 forEach
  3. 深度遍歷用 TreeWalker:原生 C++ 實現,比遞歸 childNodes 快 10-100 倍
  4. 緩存查詢結果:頻繁訪問的節點鏈路 (如編輯器光標上下文) 應緩存
  5. 避免佈局抖動:批量讀取幾何屬性後再批量寫入,或使用 requestAnimationFrame

總結

掌握 DOM 節點關係的核心在於區分節點類型 (Element vs Text vs Comment) 與集合類型 (動態 vs 靜態)。現代開發推薦:查詢用 querySelectorAll、遍歷用 TreeWalker、關係導航用 Element 專有屬性 (children, previousElementSibling 等)。本文工具函數庫採用 TypeScript 嚴格類型、JSDoc 文檔、零依賴、Tree-shaking 友好設計,可直接集成至項目工具包,作為「框架無關 DOM 工具層」的基石。

copyright © 萬盛學電腦網 all rights reserved