紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS DOM Node 介面:parentNode、contains() 等屬性與方法

JS DOM Node 介面:parentNode、contains() 等屬性與方法 特色圖片

DOM Node(Node 介面)是 DOM 的抽象基底類別(abstract base class):沒有單純的 Node 物件,所有實際的節點(node,樂詞網資訊名詞同為「節點」)都屬於它的子介面,最常見的是 Document、Element 與 DocumentFragment。

MDN 另外說明,Attr、CharacterData(Text、Comment 等都繼承它)、DocumentType 這些各種節點也都以 Node 為基礎,所以它們能用同一套方式操作。

本文只整理 Node 介面本身的屬性與方法,並示範其中最常用的幾個。DOM 樹與節點類型的整體觀念,可前往「JS DOM 文件物件模型:節點與樹狀結構」一文。

Node 是抽象類別

因為所有節點都繼承 Node,不論拿到的是元素、文字還是整份文件,都能用 instanceof Node 判斷。直接用 new Node() 建立物件則不行:

<div id="box">
  <p id="first">One</p>
  <!-- note -->
  <p id="second">Two</p>
</div>
function errorName(fn) {
  try {
    fn();
    return "no error";
  } catch (e) {
    return e.name;
  }
}

const box = document.getElementById("box");

console.log(box instanceof Node);                              // true
console.log(document instanceof Node);                         // true
console.log(document.createTextNode("x") instanceof Node);     // true
console.log(document.createComment("c") instanceof Node);      // true
console.log(errorName(() => new Node()));                      // TypeError

建立節點要用對應的方法,例如 document.createElement()、document.createTextNode()。

MDN 提醒:基底的某個功能不適用於某種子介面時,該節點可能回傳 null,或丟出例外。例如對不能有子節點的節點類型新增子節點,就會丟出例外。

屬性與方法一覽

下面是 MDN 列出的 Node 實例屬性與方法,依用途分類。Node 也繼承 EventTarget,所以還有 addEventListener() 等方法。

用途屬性方法
在樹中移動parentNode、parentElement、childNodes、firstChild、lastChild、nextSibling、previousSiblinghasChildNodes()
節點資料nodeName、nodeType、nodeValue、textContent無
所屬文件與連結狀態ownerDocument、isConnected、baseURIgetRootNode()
比較與判斷無contains()、compareDocumentPosition()、isEqualNode()、isSameNode()
修改子節點無appendChild()、insertBefore()、replaceChild()、removeChild()、cloneNode()、normalize()
命名空間無isDefaultNamespace()、lookupPrefix()、lookupNamespaceURI()

此外還有 selectstart 事件,使用者在這個節點開始新的選取範圍時觸發。

nodeType、textContent、appendChild()、removeChild()、cloneNode() 本文只列名稱,不展開。命名空間相關的三個方法主要用在 XML 與 SVG,也不在本文範圍。

在樹中移動:親子與兄弟

  • parentNode 取得父節點(parent node,樂詞網電子計算機名詞譯為「上代節點」)。
  • childNodes 取得所有子節點,firstChild、lastChild 取得第一個與最後一個子節點。
  • nextSibling、previousSibling 取得前後的兄弟節點(sibling,樂詞網電子計算機名詞譯為「同輩份」)。

找不到時,這幾個屬性都回傳 null。

這些屬性回傳的是任何類型的節點。MDN 說明,瀏覽器會用文字節點表示原始碼裡的空白,所以標籤之間的換行與縮排也算節點:

const children = box.childNodes;

console.log(children.length);                                   // 7
console.log(Array.from(children, (n) => n.nodeName).join());   // #text,P,#text,#comment,#text,P,#text
console.log(box.firstChild.nodeName);                           // #text
console.log(box.lastChild.nodeName);                            // #text
console.log(box.hasChildNodes());                               // true

#text、#comment 是文字節點與註解節點的 nodeName。想只取得元素時,MDN 建議改用 Element 上的對應屬性,例如 firstElementChild、nextElementSibling、children:

const first = document.getElementById("first");

console.log(first.nextSibling.nodeName);                  // #text
console.log(first.nextSibling.nextSibling.nodeName);      // #comment
console.log(first.previousSibling.nodeName);              // #text
console.log(first.nextElementSibling.id);                 // second
console.log(box.firstElementChild.id);                    // first
console.log(box.children.length);                         // 2

parentNode 與 parentElement 的差別在父節點的類型:parentNode 回傳任何類型的父節點,parentElement 只在父節點是元素時回傳,否則是 null。MDN 也說明,Document 與 DocumentFragment 不會有父節點,剛建立還沒放進樹裡的節點也是 null:

const html = document.documentElement;

console.log(html.parentNode === document);                   // true
console.log(html.parentElement);                             // null
console.log(first.parentNode === box);                       // true
console.log(first.parentElement === box);                    // true
console.log(document.createElement("div").parentNode);       // null

childNodes 是即時更新的 NodeList

childNodes 回傳的是即時(live)的 NodeList:子節點增減時,這個集合會自動更新。MDN 也說明,多次讀取 childNodes 拿到的是同一個 NodeList:

<ul id="list"><li>A</li><li>B</li><li>C</li></ul>
const list = document.getElementById("list");
const live = list.childNodes;

console.log(live.length);                       // 3

list.appendChild(document.createElement("li"));

console.log(live.length);                       // 4
console.log(list.childNodes === live);          // true

NodeList 本身的屬性與方法不在本文範圍。

nodeName 與 nodeValue

nodeName 是節點的名稱,格式依節點類型而定:元素是對應的標籤名稱(例如 AUDIO),文字節點是 #text,Document 是 #document。nodeValue 是節點的值,MDN 整理的對照如下:

節點nodeValue
Text、Comment、CDATASection節點的文字內容
Attr屬性的值
ProcessingInstruction除了目標(target)以外的全部內容
Element、Document、DocumentFragment、DocumentTypenull

nodeValue 定義為 null 的節點,設定它沒有任何作用:

const paragraph = document.getElementById("first");
const text = paragraph.firstChild;
const note = box.childNodes[3];

console.log(paragraph.nodeName, paragraph.nodeValue);      // P null
console.log(text.nodeName, text.nodeValue);                // #text One
console.log(note.nodeName, JSON.stringify(note.nodeValue));   // #comment " note "
console.log(document.nodeName, document.nodeValue);        // #document null

paragraph.nodeValue = "ignored";
text.nodeValue = "Uno";

console.log(paragraph.textContent);                        // Uno

判斷節點之間的關係

contains():是不是後代

contains(otherNode) 回傳 otherNode 是不是這個節點的後代,包括自己、直接子節點、子節點的子節點,依此類推。MDN 特別註明:一個節點也被視為「包含」自己。參數不能省略,但可以傳 null,傳 null 一律回傳 false:

console.log(box.contains(first));                          // true
console.log(box.contains(box));                            // true
console.log(first.contains(box));                          // false
console.log(box.contains(null));                           // false
console.log(box.contains(document.createElement("p")));   // false

compareDocumentPosition():相對位置

compareDocumentPosition(otherNode) 回傳 otherNode 相對於呼叫它的節點的位置。回傳值是位元遮罩(bitmask,樂詞網電子工程名詞譯為「位元遮罩」),由 Node 的常數組合而成,兩個節點相同時是 0:

常數值意思
Node.DOCUMENT_POSITION_DISCONNECTED1兩個節點在不同文件,或同一文件的不同樹
Node.DOCUMENT_POSITION_PRECEDING2otherNode 在這個節點之前
Node.DOCUMENT_POSITION_FOLLOWING4otherNode 在這個節點之後
Node.DOCUMENT_POSITION_CONTAINS8otherNode 是這個節點的祖先
Node.DOCUMENT_POSITION_CONTAINED_BY16otherNode 是這個節點的後代
Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC32結果依賴實作,不保證可移植

可能同時設定好幾個位元。MDN 的例子:otherNode 在文件中較前面,而且是這個節點的祖先,CONTAINS 與 PRECEDING 兩個位元都會設定,值是 10。因為回傳的是位元遮罩,判斷時要用位元 AND(&)運算子:

const second = document.getElementById("second");

console.log(first.compareDocumentPosition(second));            // 4
console.log(second.compareDocumentPosition(first));            // 2
console.log(first.compareDocumentPosition(box));               // 10
console.log(box.compareDocumentPosition(first));               // 20
console.log(first.compareDocumentPosition(first));             // 0

const stray = document.createElement("p");

console.log(first.compareDocumentPosition(stray) & Node.DOCUMENT_POSITION_DISCONNECTED);   // 1

if (first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING) {
  console.log("second 在 first 之後");                           // second 在 first 之後
}

isEqualNode() 與 isSameNode()

isEqualNode() 比較兩個節點的內容是否相等:型態、定義特徵(例如元素的 id、子節點數量)與屬性都要符合。isSameNode() 則是 === 嚴格相等運算子的舊式別名(legacy alias),判斷的是兩個變數是不是指向同一個物件。MDN 說明不需要使用 isSameNode(),直接用 ===。兩個方法的參數都不能省略,但可以傳 null:

<div class="twin">Same</div>
<div class="twin">Same</div>
<div class="twin">Other</div>
const twins = document.querySelectorAll(".twin");

console.log(twins[0].isEqualNode(twins[1]));    // true
console.log(twins[0].isEqualNode(twins[2]));    // false
console.log(twins[0].isEqualNode(null));        // false
console.log(twins[0].isSameNode(twins[1]));     // false
console.log(twins[0].isSameNode(twins[0]));     // true
console.log(twins[0] === twins[1]);             // false

前兩個 div 內容與屬性都一樣,所以 isEqualNode() 是 true,但它們是兩個不同的物件,isSameNode() 與 === 都是 false。

isConnected、ownerDocument 與 getRootNode()

isConnected 回傳節點有沒有(直接或間接)連到文件。ownerDocument 回傳節點所屬的 Document,節點本身就是 Document 時是 null。getRootNode() 回傳節點所在那棵樹的根:

const wrapper = document.createElement("p");
const inner = document.createElement("span");
wrapper.append(inner);

console.log(inner.isConnected);                      // false
console.log(inner.getRootNode() === wrapper);        // true

document.body.appendChild(wrapper);

console.log(inner.isConnected);                      // true
console.log(inner.getRootNode() === document);       // true
console.log(inner.ownerDocument === document);       // true
console.log(document.ownerDocument);                 // null

還沒放進文件時,inner 所在那棵樹的根是 wrapper 本身。MDN 說明,沒有父節點的節點,根就是它自己。放進文件之後,根變成 document。

getRootNode() 可以傳入 { composed: true }。預設(false)遇到 Shadow DOM 時,回傳的是 ShadowRoot;設成 true,則會穿過 shadow root,回傳更外層的根:

<div id="host"></div>
const host = document.getElementById("host");
const shadow = host.attachShadow({ mode: "open" });
shadow.innerHTML = '<span id="shadowChild">in shadow</span>';

const shadowChild = shadow.querySelector("#shadowChild");

console.log(shadowChild.getRootNode() === shadow);                          // true
console.log(shadowChild.getRootNode({ composed: false }) === shadow);       // true
console.log(shadowChild.getRootNode({ composed: true }).nodeName);          // #document

MDN 補充:Attr 節點的 isConnected 一律是 false,因為屬性不屬於節點樹,沒有父節點,自己就是自己的根。

修改子節點

insertBefore():插入在參考節點之前

parent.insertBefore(newNode, referenceNode) 把 newNode 插入 parent 的子節點中,位置在 referenceNode 之前,回傳插入的節點。幾個要點都出自 MDN:

  • 如果 newNode 已經在文件裡,會從原本的位置移到新位置,不會複製。一個節點不可能同時在兩個位置。
  • referenceNode 不能省略,要明確傳入節點或 null。傳 null 時,newNode 插在所有子節點的最後面。
  • 如果 newNode 是 DocumentFragment,整個片段的內容會被移進去,回傳的是已經清空的片段。
  • 沒有 insertAfter()。要插在某節點之後,用 insertBefore(newNode, node.nextSibling);沒有下一個兄弟節點時,nextSibling 是 null,剛好插在最後。
<ol id="steps"><li id="s1">one</li><li id="s3">three</li></ol>
const steps = document.getElementById("steps");
const ids = () => Array.from(steps.children, (li) => li.id).join();

const s1 = document.getElementById("s1");
const s3 = document.getElementById("s3");

const s2 = document.createElement("li");
s2.id = "s2";
s2.textContent = "two";

console.log(steps.insertBefore(s2, s3) === s2);   // true
console.log(ids());                               // s1,s2,s3

const s4 = document.createElement("li");
s4.id = "s4";
steps.insertBefore(s4, s3.nextSibling);           // s3 是最後一個,nextSibling 為 null

console.log(ids());                               // s1,s2,s3,s4

steps.insertBefore(s4, s1);                       // 已在文件裡的節點會被移動

console.log(ids());                               // s4,s1,s2,s3
console.log(steps.children.length);               // 4

最後一步 s4 被移到最前面,steps 仍然是 4 個子元素。

referenceNode 必須是 parent 的子節點。DOM 規範的 pre-insert 驗證規定:參考節點不是 null,而且它的父節點不是 parent 時,丟出 NotFoundError:

console.log(errorName(() => steps.insertBefore(document.createElement("li"), document.body)));   // NotFoundError

replaceChild():取代子節點

parent.replaceChild(newChild, oldChild) 用 newChild 取代 parent 的子節點 oldChild,回傳被取代的 oldChild。MDN 提醒參數順序是「新的在前、舊的在後」,不太直覺;如果只處理元素,Element.replaceWith() 比較好讀。如果 newChild 原本就在文件裡,會先從原位置移除:

const old = document.getElementById("s2");
const fresh = document.createElement("li");
fresh.id = "s2b";
fresh.textContent = "TWO";

console.log(steps.replaceChild(fresh, old) === old);   // true
console.log(ids());                                    // s4,s1,s2b,s3
console.log(old.parentNode);                           // null

MDN 列出兩種常見例外:

  • NotFoundError:oldChild 的父節點不是目前的節點。
  • HierarchyRequestError:違反 DOM 樹的限制,例如 newChild 是 parent 的祖先,取代後會形成循環。
console.log(errorName(() => steps.replaceChild(document.createElement("li"), old)));   // NotFoundError
console.log(errorName(() => steps.replaceChild(document.body, s1)));                   // HierarchyRequestError

第一行的 old 已經被取代,不再是 steps 的子節點。第二行的 document.body 是 steps 的祖先。

normalize():合併相鄰的文字節點

normalize() 把節點以下的整個子樹整理成「正規化」的形式:不留空的文字節點,也沒有相鄰的文字節點。MDN 說明它與 Text.splitText() 的作用相反:

const holder = document.createElement("div");
holder.appendChild(document.createTextNode("Part 1 "));
holder.appendChild(document.createTextNode("Part 2 "));
holder.appendChild(document.createTextNode(""));

console.log(holder.childNodes.length);                       // 3

holder.normalize();

console.log(holder.childNodes.length);                       // 1
console.log(JSON.stringify(holder.firstChild.nodeValue));    // "Part 1 Part 2 "

清空所有子節點

MDN 在 Node 頁面給了清空子節點的寫法:只要還有 firstChild,就把它用 removeChild() 移除。因為 childNodes 是即時更新的,所以每次迴圈都是重新取得第一個子節點。MDN 也提到另一種做法,是把 textContent 設成空字串:

<div id="trash"><p>1</p><p>2</p><p>3</p></div>
<div id="trash2"><p>1</p><p>2</p></div>
function removeAllChildren(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

const trash = document.getElementById("trash");
const trash2 = document.getElementById("trash2");

removeAllChildren(trash);
trash2.textContent = "";

console.log(trash.childNodes.length);     // 0
console.log(trash2.childNodes.length);    // 0

走訪所有後代節點

MDN 的另一個範例,是用遞迴(recursion)對根節點與所有後代節點各執行一次回呼函式。沒有給回呼函式時,回傳包含所有節點的陣列:

function eachNode(rootNode, callback) {
  if (!callback) {
    const nodes = [];
    eachNode(rootNode, (node) => {
      nodes.push(node);
    });
    return nodes;
  }

  if (callback(rootNode) === false) {
    return false;
  }

  if (rootNode.hasChildNodes()) {
    for (const node of rootNode.childNodes) {
      if (eachNode(node, callback) === false) {
        return;
      }
    }
  }
}

const all = eachNode(document.getElementById("steps"));

console.log(all.length);                                          // 8
console.log(all.map((n) => n.nodeName).join());                   // OL,LI,LI,#text,LI,#text,LI,#text

範例中 s4 是剛建立、沒有文字內容的 li,所以它底下沒有文字節點,總共是 8 個節點。

回呼函式回傳 false 時,會中止目前這一層的遞迴,回到上一層繼續。這可以用來找到目標後提早結束,MDN 用它示範在網頁裡搜尋含有特定字串的文字節點。

注意事項

  1. Node 不能直接建立:它是抽象類別,節點要用 createElement() 這類方法建立。
  2. 空白也是節點:firstChild、nextSibling、childNodes 會碰到空白形成的文字節點,只要元素時改用 firstElementChild、children 等屬性。
  3. childNodes 是即時的:增減子節點時它會跟著變,迴圈裡修改子節點要特別小心。
  4. contains() 包含自己:判斷「是不是別人的後代」時,要先排除相同節點。
  5. compareDocumentPosition() 回傳位元遮罩:要用 & 判斷,不要直接用 === 比較。
  6. isEqualNode() 比內容,=== 比物件:內容一樣的兩個節點,物件不同。
  7. insertBefore() 的第二個參數不能省略,沒有 insertAfter()。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data,查詢日期 2026-11-24):Node 介面從 Chrome 1、Firefox 1、Safari 1 開始支援。各成員的起始版本如下,BCD 沒有 Node.js 與 Deno 的支援紀錄:

成員ChromeFirefoxSafari
parentNode、childNodes、nextSibling111.1~1.2
parentElement191.1
contains()1691.1
compareDocumentPosition()214
isEqualNode()113
isSameNode()1483
isConnected514910
getRootNode()545310.1

補充說明:範例在 Chrome 158 執行;Node.js v22.20.0 沒有 Node 全域物件,typeof Node 是 undefined。MDN 的範例有 removeAllChildren()、eachNode() 與各方法的小範例,其餘是本文自己的示範。

參考資料與延伸閱讀

發佈留言