文件:prepend() 方法
Document.prepend() 方法在文件的第一個子節點之前插入一組 Node 物件或字串。字串將作為等效的 Text 節點插入。
此方法在文件前面新增子節點。要在樹中的任意元素前面新增子節點,請參閱 Element.prepend()。
語法
js
prepend(param1)
prepend(param1, param2)
prepend(param1, param2, /* …, */ paramN)
引數
param1, …,paramN-
要插入的一組
Node物件或字串。
返回值
無(undefined)。
異常
HierarchyRequestErrorDOMException-
在節點無法插入到層次結構中的指定位置時丟擲。
示例
在文件前面新增根元素
如果您嘗試在現有 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① |
瀏覽器相容性
載入中…