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 (

) with new content when the button is clicked −



 
HTML DOM replaceChild()



Click the button to replace the paragraph with a new div.

This is a paragraph.

Example 2: Replacing List Item

Following is another example of the HTML DOM replaceChild() method. We use this method to replace a list (

  • ) items with a new one −

    
    
     
    HTML DOM replaceChild()
    
    
    
    

    Click the button to replace the first list item with a new list item.

    • Item 1
    • Item 2
    • Item 3

    Supported Browsers

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