JavaScript replaceChild() Method

Summary: in this tutorial, you will learn how to use the JavaScript Node.replaceChild() method to replace an HTML element with a new one.

To replace an HTML element, you use the node.replaceChild() method:

parentNode.replaceChild(newChild, oldChild);

In this method, the newChild is the new node to replace the oldChild node which is the old child node to be replaced.

Suppose that you have the following list of items:

<ul id="menu">
    <li>Homepage</li>
    <li>Services</li>   
    <li>About</li>
    <li>Contact</li>
</ul>

The following example creates a new list item element and replaces the first list item element in the menu with the new one:

let menu = document.getElementById('menu');

// create a new node
let li = document.createElement('li');
li.textContent = 'Home';

// replace the first list item
menu.replaceChild(li, menu.firstElementChild);

Put it all together.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript DOM: Replace Elements</title>
</head>
<body>
    <ul id="menu">
        <li>Homepage</li>
        <li>Services</li>
        <li>About</li>
        <li>Contact</li>
    </ul>
    <script>
        let menu = document.getElementById('menu');
        
        // create a new node
        let li = document.createElement('li');
        li.textContent = 'Home';

        // replace the first list item
        menu.replaceChild(li, menu.firstElementChild);
    </script>
</body>
</html>

Summary #

  • Use Node.replaceChild() to replace a child element of a node with a new element.

Quiz #

Quiz

Understanding replaceChild() Method

5 questions

Test your understanding of the replaceChild() method and its usage in JavaScript.

Was this helpful?