Replace a DOM Element

To replace a DOM element in the DOM tree, you follow these steps:

See the following HTML document:

<html>
<head>
  <title>Replace a DOM element</title>
</head>
<body>

  <ul>
    <li><a href="/home">Home</a></li>
    <li><a href="/service">Service</a></li>
    <li><a href="/about">About</a></li>
  </ul>

  <script src="js/app.js"></script>
</body>
</html>Code language: HTML, XML (xml)

To select the last list item element, you follow the above steps:

First, select the last list item using the querySelector() method:

const listItem = document.querySelector("li:last-child");Code language: JavaScript (javascript)

Second, create a new list item element:

const newItem = document.createElement('li');
newItem.innerHTML = '<a href="/products">Products</a>';Code language: JavaScript (javascript)

Finally, get the parent of the target element and call the replaceChild() method:

listItem.parentNode.replaceChild(newItem, listItem);Code language: CSS (css)

Here is the output:

Was this tutorial helpful ?