此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Document:append() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2018年4月⁩.

Document.append() 方法会在文档的最后一个子节点后插入一组节点对象或字符串对象。字符串对象被插入为相同文本节点。

此方法将一个子元素追加到 Document 中。要向树中的任意元素添加子元素,请参阅 Element.append()

语法

js
append(param1)
append(param1, param2)
append(param1, param2, /* …, */ paramN)

参数

param1, …, paramN

要插入的一组 Node 或字符串对象。

返回值

无(undefined)。

异常

HierarchyRequestError DOMException

当节点无法插入层次结构中的指定点时抛出异常。

示例

向文档添加根元素

如果你尝试在现有 HTML 文档中添加元素,可能会抛出 HierarchyRequestError DOMException,因为 <html> 元素已经存在。

js
let html = document.createElement("html");
document.append(html);
// HierarchyRequestError: The operation would yield an incorrect node tree.

如果创建的新文档没有任何现有元素,你可以添加一个 HTML 根元素(或 SVG 根元素):

js
let doc = new Document();
let html = document.createElement("html");
doc.append(html);

doc.children; // HTMLCollection [<html>]

规范

Specification
DOM
# ref-for-dom-parentnode-append①

浏览器兼容性

参见