revision:
The Element.replaceWith() method replaces this Element in the children list of its parent with a set of Node or string objects. String objects are inserted as equivalent Text nodes.
This method searches a string for a value or a regular expression. It returns a new string with the value(s) replaced. It does not change the original string.
replaceWith(param1) replaceWith(param1, param2) replaceWith(param1, param2, /* … ,*/ paramN)
Parameters:
param1, …, paramN : A set of Node or string objects to replace.
const div = document.createElement("div"); const p = document.createElement("p"); div.appendChild(p); const span = document.createElement("span"); p.replaceWith(span); console.log(div.outerHTML); // "<div><span></span></div>"
see console.log
<div> <p>see console.log</p> <div id="replace-1"></div> </div> <script> const div1 = document.createElement("div"); const p1 = document.createElement("p"); const header1 = document.createElement("h1"); div1.appendChild(p1); p1.appendChild(header1); console.log(div1); document.getElementById("replace-1").innerHTML = div1;
see console.log
<div> <p>see console.log</p> <p id="replace-2"></p> </div> <script> const div = document.createElement("div"); const p = document.createElement("p"); div.appendChild(p); console.log(div); /* <div> <p></p> </div> */ p.replaceWith("Hello World!"); console.log(div); document.getElementById("replace-2").innerHTML = div; </script>
original sentence: The JavaScript Guide is a nice resource to learn JavaScript programming.
modified sentence : The JavaScript Guide is a nice resource to learn JavaScript programming.
<div> <p>original sentence: <span>The <span>JavaScript Guide</span> is a nice resource to learn JavaScript programming.</span></p> <p>modified sentence : <span>The <span id="replace-4">JavaScript Guide</span> is a nice resource to learn JavaScript programming.</span></p> </div> <script> let span = document.querySelector('#replace-4'); let strong = document.createElement('strong'); strong.textContent = span.textContent; span.replaceWith(strong); </script>