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.
The method takes two parameters:
Let’s write a code to replace a list item with a newly created item.
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.
When we click the button, the second li
list item is replaced with the new text node.