What is the DOM replaceChild() method?

Overview

In this shot, we will learn how to replace a child element with a newly created child element.

The replaceChild() method replaces the old child element with a new one.

Parameters

The method takes two parameters:

  1. The reference of the new child node.
  2. The present or old child node that will be replaced in the document.

Code

Let’s write a code to replace a list item with a newly created item.

Explanation

  • In line 5, we have a ul element (unordered list) with 3 li (list items) inside it.

  • In line 7, we include a paragraph tag to display text.

  • In line 9, we write a button tag with a change() function that will be called when the user clicks on it.

  • In line 12, we write the JavaScript code in the script tag. We define a change() function that will be called when a user clicks on the button from the HTML page.

  • In line 13, we use createTextNode() to create a new text node; this node will be replaced with the list item.

  • In line 14, we use getElementById() to select the ul list and then use childNodes[1] to select the second list item. To select the first li, replace 1 with 0 in the childNodes array.

  • In line 15, we replace the new text node with the present text node in the second li of the list. We apply the replaceChild() method on the list element. The first parameter is the new text node (newnode) and the second parameter is the old or present text node (firstLi.childNodes[0]). firstLi.childNodes[0] returns the first text node in the li and replaces it.

Output

When we click the button, the second li list item is replaced with the new text node.