The replaceWith() method replaces the node in the children list of its parent with a set of Node or DOMString objects. DOMString objects are equivalent to Text nodes. Here, the One Child element is replaced by the Other Child element.
Syntax:
ChildNode.replaceWith(Node);
Parameters:
- ChildNode: The ChildNode which is to be replaced.
- Node: The Node with which ChildNode is replaced.
Return Value: No return value.
Example: In this example, childNode named childPara (<p> element) is replaced with a node named childDiv (<div> element) by using this method.
HTML
<!DOCTYPE html> < html > Â
< head >     < title >           replaceWith() method       </ title > </ head > Â
< body > Â Â Â Â < h1 >Welcome to neveropen</ h1 > Â Â Â Â Â Â Â < script > Â Â Â Â Â Â Â Â let parent = document.createElement("div"); Â Â Â Â Â Â Â Â parent.innerHTML = "Parent of the document"; Â
        let childPara = document.createElement("p");         childPara.innerHTML = "Child ParaGraph";         parent.appendChild(childPara);         console.log(parent.outerHTML); Â
        let childDiv = document.createElement("div");         childDiv.innerHTML = "Child Div";         childPara.replaceWith(childDiv);         console.log(parent.outerHTML);     </ script >    </ body > Â
</ html > |
Output:
In the console, it can be seen:
- In line 12, Before applying the replaceWith() method, outerHTML of the parent element has <p> element as childNode.
- In line 16, After applying this method, the parent element has <div> element replaced as ChildNode.
Supported Browsers:
- Google Chrome 54 and above
- Edge 17 and above
- Firefox 49 and above
- Internet Explorer not supported
- Opera 39 and above
- Safari 10 and above