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:
- The reference of the new child node.
- 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
ulelement (unordered list) with 3li(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 theullist and then usechildNodes[1]to select the second list item. To select the firstli, replace1with0in thechildNodesarray. -
In line 15, we replace the new text node with the present text node in the second
liof the list. We apply thereplaceChild()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 theliand replaces it.
Output
When we click the button, the second li list item is replaced with the new text node.