CharacterData:replaceWith() 方法

Baseline 已廣泛支援

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

CharacterData 介面的 replaceWith() 方法用一組 Node 物件或字串替換此節點在其父節點的子節點列表中的位置。

字串會被插入為 Text 節點;該字串被當作引數傳遞給 Text() 建構函式。

語法

js
replaceWith(...nodes)

引數

nodes 可選

將替換當前節點的 Node 物件或字串的逗號分隔列表。

注意: 如果不傳遞任何引數,此方法將從 DOM 樹中移除該節點。

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

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

示例

html
<p id="myText">Some text</p>
js
let text = document.getElementById("myText").firstChild;
let em = document.createElement("em");
em.textContent = "Italic text";

text.replaceWith(em); // Replace `Some text` by `Italic text`

規範

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

瀏覽器相容性

另見