文件:append() 方法

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

Document.append() 方法將在文件的最後一個子節點之後插入一組 Node 物件或字串。字串將被插入為等效的 Text 節點。

此方法將一個子節點追加到 Document。要追加到樹中的任意元素,請參閱 Element.append()

語法

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

引數

param1, …, paramN

要插入的一組 Node 物件或字串。

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

在節點無法插入到層次結構中的指定位置時丟擲。

示例

將根元素追加到文件

如果您嘗試將一個元素追加到一個現有的 HTML 文件中,並且該文件中已存在一個 <html> 元素,則可能會丟擲 HierarchyRequestError DOMException

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>]

規範

規範
DOM
# ref-for-dom-parentnode-append①

瀏覽器相容性

另見