JavaScript replaceWith function

CodingTute

JavaScript replaceWith function

The replaceWith() function in javascript is used to replace an Element in the child list of the parent with a set of Node or DOMString objects.

In simpler terms, the javascript replaceWith() method will replace an Element or Node with other.

Example of using replaceWith()

const div = document.createElement("div");
const p = document.createElement("p");
const txt = document.createTextNode("Text Content");
p.appendChild(txt);
div.appendChild(p);

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

const span = document.createElement("span");
const newTxt = document.createTextNode("New Text Content");
span.appendChild(newTxt);
p.replaceWith(span);

console.log(div.outerHTML);
// "<div><span>New Text Content</span></div>"

Output

<div><p>Text Content</p></div>

<div><span>New Text Content</span></div>

Explanation

At the first, we created a parent element div. We created another element p with some text content in it, then append the p element as child element to div.

Now we will create another span element and add some text to it. With the help of the replaceWith() method, we will replace the p element with the span element in the div.