Element: after() 方法

Baseline 已廣泛支援

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

Element.after() 方法在 Element 的父級子節點列表中,緊跟在 Element 之後插入一組 Node 物件或字串。字串將被插入為等效的 Text 節點。

語法

js
after(node1)
after(node1, node2)
after(node1, node2, /* …, */ nodeN)

引數

node1, …, nodeN

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

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

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

示例

插入元素

js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.after(span);

console.log(container.outerHTML);
// "<div><p></p><span></span></div>"

插入文字

js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);

p.after("Text");

console.log(container.outerHTML);
// "<div><p></p>Text</div>"

插入元素和文字

js
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.after(span, "Text");

console.log(container.outerHTML);
// "<div><p></p><span></span>Text</div>"

規範

規範
DOM
# ref-for-dom-childnode-after①

瀏覽器相容性

另見