HTML | DOM replaceWith() Method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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.

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.