Skip to content
Related Articles

Related Articles

Improve Article

HTML | DOM replaceWith() Method

  • Last Updated : 21 Jun, 2020

The replaceWith() method replaces the a node in the children list of its parent with a set of Node or DOMString objects. DOMString objects are equivalent to Text nodes. Here, One child element is replaced by 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, I had replaced childNode named childPara (<p> element) with a node named childDiv (<div> element) by using this method.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>replaceWith() method</title>
    <script>
        var parent = document.createElement("div");
        parent.innerHTML = "Parent of the document";
  
        var childPara = document.createElement("p");
        childPara.innerHTML = "Child ParaGraph";
        parent.appendChild(childPara);
        console.log(parent.outerHTML);
  
        var childDiv = document.createElement("div");
        childDiv.innerHTML = "Child Div";
        childPara.replaceWith(childDiv);
        console.log(parent.outerHTML);
    </script>
</head>
  
<body>
    <h1>Welcome to GeeksforGeeks</h1>
</body>
  
</html>

Output:

In console, it can be seen:

  • In line 12, Before applying replaceWith() method , outerHTML of parent element has <p> element as childNode.
  • In line 16, After applying this method , parent element has <div> element replaced as ChildNode.

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :