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);Code language: CSS (css)

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>Code language: HTML, XML (xml)

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);Code language: JavaScript (javascript)

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>Code language: HTML, XML (xml)

Summary

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

Quiz

Was this tutorial helpful ?