Node: appendChild() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Node 接口的 appendChild() 方法将一个节点添加到指定父节点子节点列表的末尾。

注意: 如果提供的子节点是文档中现有节点的引用,appendChild() 会将其从当前位置移动到新位置。

如果提供的子节点是 DocumentFragment,则 DocumentFragment 的所有内容都会被移动到指定父节点的子节点列表中。

appendChild() 返回新附加的节点,如果子节点是 DocumentFragment,则返回被清空的片段。

注意: 与此方法不同,Element.append() 方法支持多个参数和附加字符串。如果你的节点是元素,可以优先使用它。

语法

js
appendChild(child)

参数

child

要附加到给定父节点(通常是元素)的节点。

返回值

一个 Node,它是被附加的子节点(child),除非 child 是一个 DocumentFragment,在这种情况下,返回空的 DocumentFragment

异常

HierarchyRequestError DOMException

当违反 DOM 树的约束时抛出,即发生以下任一情况时:

描述

如果提供的子节点是文档中现有节点的引用,appendChild() 会将其从当前位置移动到新位置——在将其附加到另一个节点之前,不需要将其从其父节点中删除。这意味着一个节点不能同时存在于文档的两个位置。可以使用 Node.cloneNode() 方法在将节点附加到新父节点之前复制该节点。使用 cloneNode 创建的副本不会自动保持同步。

appendChild() 返回新附加的节点,而不是父节点。这意味着你可以在创建新节点后立即附加它,而不会丢失对它的引用。

js
const paragraph = document.body.appendChild(document.createElement("p"));
// You can append more elements to the paragraph later

另一方面,你不能以 链式调用 API 的方式(例如 jQuery)使用 appendChild()

js
// This doesn't append three paragraphs:
// the three elements will be nested instead of siblings
document.body
  .appendChild(document.createElement("p"))
  .appendChild(document.createElement("p"))
  .appendChild(document.createElement("p"));

示例

向 body 追加一个段落

js
// Create a new paragraph element, and append it to the end of the document body
const p = document.createElement("p");
document.body.appendChild(p);

创建嵌套的 DOM 结构

在此示例中,我们尝试使用尽可能少的临时变量来创建嵌套的 DOM 结构。

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

document.body.appendChild(fragment);

它生成以下 DOM 树:

html
<section>
  <ul>
    <li>hello world</li>
  </ul>
</section>

规范

规范
DOM
# dom-node-appendchild

浏览器兼容性

另见