文档:prepend() 方法

Baseline 已广泛支持

此功能已成熟,可跨多种设备和浏览器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有浏览器中可用。

Document.prepend() 方法在文档的第一个子节点之前插入一组 Node 对象或字符串。字符串将作为等效的 Text 节点插入。

此方法在文档前面添加子节点。要在树中的任意元素前面添加子节点,请参阅 Element.prepend()

语法

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

参数

param1, …, paramN

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

返回值

无(undefined)。

异常

HierarchyRequestError DOMException

在节点无法插入到层次结构中的指定位置时抛出。

示例

在文档前面添加根元素

如果您尝试在现有 HTML 文档前面添加元素,由于已存在 <html> 元素,可能会抛出 HierarchyRequestError DOMException

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

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

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

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

规范

规范
DOM
# ref-for-dom-parentnode-prepend①

浏览器兼容性

另见