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

Javascript

JS appendChild():把節點加到父節點尾端的用法與回傳值

JS appendChild():把節點加到父節點尾端的用法與回傳值 特色圖片

appendChild() 是 Node 介面的方法,把一個節點加到指定父節點的子節點清單最後面。它只接受一個 Node 物件,回傳的是被加入的那個節點,不是父節點。

如果傳進去的節點本來就在文件裡,appendChild() 會把它從原位置移到新位置,不會複製。DOM 樹與節點的整體概念請看「JS DOM 文件物件模型:節點與樹狀結構」,本文只談 appendChild() 自己。

語法與回傳值

parent.appendChild(child)
項目說明
參數 child要加到 parent 子節點清單尾端的節點,通常是元素(element)
回傳值被加入的節點 child;如果 child 是 DocumentFragment,回傳的是已經清空的 DocumentFragment
例外違反 DOM 樹的限制時,丟出 HierarchyRequestError 這個 DOMException

依 MDN 的 browser-compat-data,這個方法屬於標準規範,沒有標示棄用或實驗性。

基本用法:建立元素再加進去

appendChild() 常和 document.createElement() 搭配:先建立新元素,再加到某個父節點底下。用下面這段 HTML 示範:

<div id="box"></div>
<ul id="todo"><li id="a">寫文章</li><li id="b">改程式</li><li id="c">測連結</li></ul>
<ul id="done"></ul>
const box = document.getElementById("box");

const p = document.createElement("p");
p.textContent = "Hello";
const returned = box.appendChild(p);

console.log(box.children.length);        // 1
console.log(returned === p);             // true
console.log(box.lastChild === p);        // true

加入的節點不一定是元素。文字節點也可以,例如用 document.createTextNode() 建立的節點(另有「JS document.createTextNode() 建立文字節點」一文):

const text = box.appendChild(document.createTextNode("尾端文字"));

console.log(text.nodeType);              // 3
console.log(box.childNodes.length);      // 2
console.log(box.lastChild === text);     // true

每次呼叫都是加到「目前最後面」,所以後加的節點會排在先加的後面。

回傳的是被加入的節點

appendChild() 回傳的是 child,不是 parent。MDN 指出這樣的好處:節點一建立就能加進去,同時還拿得到它的參照,之後可以繼續對它操作:

const paragraph = box.appendChild(document.createElement("p"));
paragraph.textContent = "第二段";

console.log(paragraph.nodeName);         // P
console.log(box.children.length);        // 2

也因為回傳的是子節點,appendChild() 不能像 jQuery 那樣連續呼叫(fluent API)來加入多個同層節點。MDN 的說明是:下面這樣寫不會得到三個並排的段落,而是三層巢狀:

const wrap = document.createElement("div");
const inner = wrap
  .appendChild(document.createElement("p"))
  .appendChild(document.createElement("p"))
  .appendChild(document.createElement("p"));

console.log(wrap.children.length);                              // 1
console.log(wrap.firstChild.firstChild.firstChild === inner);   // true
console.log(wrap.innerHTML);                                    // <p><p><p></p></p></p>

每次 appendChild() 回傳的是剛加入的子節點,下一個 appendChild() 就是對那個子節點呼叫,所以每一個都是上一個的子節點。

已存在的節點會被移動

這是 appendChild() 最需要注意的行為。依 MDN 說明,傳入的如果是文件裡已經存在的節點,appendChild() 會把它從原位置移到新位置,不需要先把它從原本的父節點移除。換句話說,一個節點不可能同時出現在文件的兩個位置。

把待辦清單的第一項移到另一個清單:

const todo = document.getElementById("todo");
const done = document.getElementById("done");
const a = document.getElementById("a");

console.log(a.parentNode === todo);       // true

done.appendChild(a);

console.log(a.parentNode === done);       // true
console.log(todo.children.length);        // 2
console.log(done.children.length);        // 1

目標也可以是同一個父節點。把已經在父節點裡的子節點再 appendChild() 一次,它就會移到最後面,等於重新排序:

const ids = () => Array.from(todo.children, (li) => li.id).join();

console.log(ids());                       // b,c

todo.appendChild(todo.firstElementChild);

console.log(ids());                       // c,b

想保留原位置、同時在新位置放一份,要先用 Node.cloneNode() 複製再加進去。MDN 說明,用 cloneNode() 複製出來的節點不會自動和原節點保持同步:

const copy = done.firstElementChild.cloneNode(true);
copy.id = "a-copy";
todo.appendChild(copy);

copy.textContent = "已複製的項目";

console.log(done.firstElementChild.textContent);   // 寫文章
console.log(todo.children.length);                 // 3

從文件裡移除節點則是另一件事,可以看「JS Element.remove():從 DOM 移除元素的用法」;Node.removeChild() 與 Node.cloneNode() 也各有專文。

加入 DocumentFragment

DocumentFragment 是一個不屬於文件的節點集合。MDN 說明,傳入的如果是 DocumentFragment,它裡面的整個內容會被移進父節點的子節點清單,回傳的則是已經清空的 DocumentFragment。

下面是 MDN 的範例,用最少的暫存變數建立巢狀結構:

const fragment = document.createDocumentFragment();
const li = fragment
  .appendChild(document.createElement("section"))
  .appendChild(document.createElement("ul"))
  .appendChild(document.createElement("li"));
li.textContent = "hello world";

const result = box.appendChild(fragment);

console.log(result === fragment);                         // true
console.log(fragment.childNodes.length);                  // 0
console.log(box.lastElementChild.outerHTML);              // <section><ul><li>hello world</li></ul></section>

產生的結構是 <section> 底下一個 <ul>,<ul> 裡有一個 <li>hello world</li>。因為 fragment 本身不在文件裡,所以先在片段裡組好結構,最後只要對文件呼叫一次 appendChild(),整段內容就一起加進去。

例外:HierarchyRequestError

加入的節點如果違反 DOM 樹的限制,appendChild() 會丟出 HierarchyRequestError(DOMException 的一種)。MDN 列出七種情況,常遇到的有:

情況說明
父節點的類型不允許有子節點父節點不是 Document、DocumentFragment 或 Element,例如文字節點
會形成循環child 是父節點本身或它的祖先
child 的類型不允許加入child 不是 DocumentFragment、DocumentType、Element 或 CharacterData
Document 會有第二個元素文件底下已經有根元素,再加一個 Element

MDN 另外列的幾種情況,與文字節點、DocumentType、DocumentFragment 放進 Document 有關。

function tryAppend(fn) {
  try {
    fn();
    return "no error";
  } catch (e) {
    return e.name;
  }
}

const holder = document.createElement("div");
const child = holder.appendChild(document.createElement("span"));

console.log(tryAppend(() => child.appendChild(holder)));                          // HierarchyRequestError
console.log(tryAppend(() => holder.appendChild(holder)));                         // HierarchyRequestError
console.log(tryAppend(() => holder.appendChild(document)));                       // HierarchyRequestError
console.log(tryAppend(() => document.appendChild(document.createElement("div"))));   // HierarchyRequestError
console.log(tryAppend(() => document.createTextNode("x").appendChild(document.createElement("b"))));   // HierarchyRequestError

這五行依序是:把祖先加進自己的子孫、把節點加進自己、加入 Document、替已經有 <html> 根元素的文件再加一個元素、把元素加進文字節點。

傳入字串或對 NodeList 呼叫會出錯

appendChild() 只接受 Node 物件,傳字串不會自動轉成文字節點,會丟出 TypeError。另外,appendChild() 是 Node 的方法,querySelectorAll() 回傳的 NodeList 本身不是節點,沒有這個方法,直接呼叫也是 TypeError:

const items = document.querySelectorAll("#todo li");

console.log(tryAppend(() => box.appendChild("文字")));               // TypeError
console.log(typeof items.appendChild);                               // undefined
console.log(tryAppend(() => items.appendChild(document.createElement("li"))));   // TypeError

要加到清單裡的某個元素,要先從 NodeList 取出那個元素,再對它呼叫。

appendChild() 與 Element.append() 的差別

MDN 的 Element.append() 頁面整理了兩者的差異:

項目Node.appendChild()Element.append()
可傳入的內容只有 Node 物件Node 物件或字串,字串會變成對應的文字節點
一次傳幾個一個多個
回傳值被加入的節點沒有回傳值(undefined)
呼叫對象任何 NodeElement

MDN 在 appendChild() 頁面也提醒:如果加入的對象是元素,可以優先考慮 Element.append()。

const target = document.createElement("div");

const r1 = target.appendChild(document.createElement("b"));
const r2 = target.append("文字", document.createElement("i"));

console.log(r1.nodeName);                // B
console.log(typeof r2);                  // undefined
console.log(target.childNodes.length);   // 3
console.log(target.innerHTML);           // <b></b>文字<i></i>

需要拿到被加入節點的參照、或要加入的是文件、文件片段這類非元素的父節點時,就用 appendChild()。

注意事項

  1. 已存在的節點是移動不是複製:要保留原節點,先用 Node.cloneNode() 複製。
  2. 回傳值是子節點:不能用連續呼叫的方式加入多個同層節點,會變成層層巢狀。
  3. 只能傳一個 Node:要加字串或多個節點,用 Element.append() 或分次呼叫。
  4. 要加很多節點時:可以先放進 DocumentFragment,最後一次加進文件。
  5. 父節點類型有限制:文字節點不能當父節點,Document 底下也只能有一個根元素。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data,查詢日期 2026-11-24):Node.appendChild() 從 Chrome 1、Edge 12、Firefox 1、Safari 1.1 開始支援。MDN 頁面標示為 Baseline「廣泛可用」,自 2015 年 7 月起各主流瀏覽器都支援。資料裡沒有 Node.js 與 Deno 的支援紀錄。

補充說明:範例在 Chrome 158 執行;Node.js 沒有 DOM,typeof Node 是 undefined。MDN 的範例涵蓋建立元素加進文件、回傳值、連續呼叫變成巢狀,以及用 DocumentFragment 建立巢狀結構;其餘是本文自己的示範。

參考資料與延伸閱讀

發佈留言