HTML DOM replaceWith() Method

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 zambiatek</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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




