HTML - DOM replaceChild() Method



The HTML DOMreplaceChild()method allows you to replace one child (i.e., old child) element with another (i.e., new child) in a parent element.

The newChild can be any type of node (element, text, comment, etc.), while the oldChild must be a child of parentNode. If the oldChild is not a child of parentNode, this method will throw a NotFoundError.

Syntax

Following is the syntax of the HTML DOM replaceChild() method −

parentElement.replaceChild(newChild, oldChild);

Parameters

This method accepts two parameters as mentioned below −

Parameter Description
newChild The new child element that will replace the existing (old) child element.
oldChild The existing child elements that will be replaced.

Return Value

This method returns the replaced child element, which has been removed from the parent element.

Example 1: Replacing a Paragraph with New Element

The following example shows the usage of the HTML DOM replaceChild() method to replace a paragraph (<p>) with new content when the button is clicked −

<![DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM replaceChild()</title>
<style>
   button{
      padding: 10px;
   }
</style>
</head>
<body>
<p>Click the button to replace the paragraph with a new div.</p>
<div id="content">
<p id="currentPara">This is a paragraph.</p>
</div>
<button onclick="replaceParagraph()">Replace Paragraph</button>
<script>
   function replaceParagraph() {
      const newDiv = document.createElement('div');
      newDiv.textContent = 'This is a new div element';
      const content = document.getElementById('content');
      const currentPara = document.getElementById('currentPara');
      content.replaceChild(newDiv, currentPara);
   }
</script>
</body>
</html>

Example 2: Replacing List Item

Following is another example of the HTML DOM replaceChild() method. We use this method to replace a list (<li>) items with a new one −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM replaceChild()</title>
<style>
   button{
      padding: 10px;
   }
</style>
</head>
<body>
<p>Click the button to replace the first list item with a new list item.</p>
<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>
<button onclick="replaceListItem()">Replace List Item</button>
<script>
   function replaceListItem() { 
       const nI=document.createElement('li');
       nI.textContent = 'New Item';
       // Get reference to the list and the first list item
       const mL=document.getElementById('myList');
       const fi=mL.querySelector('li:first-child');
       // Replace the first list item with the new list item
       mL.replaceChild(nI, fi);
   }
</script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
replaceChild() Yes Yes Yes Yes Yes
html_dom.htm
Advertisements