To replace a DOM element with another element, you can use the replaceChild() method. This method replaces a child node with a new node.

Let us say you've got the following list:

<ul>
        <li>🍔</li>
        <li>🍕</li>
        <li>🍹</li>
        <li>🍲</li>
        <li>🍩</li>
    </ul>

Now you want to replace the last list item with another item. Just follow the following steps:

  1. Select the target element that you want to replace.
  2. Create a new DOM element with all the content you need.
  3. Select the parent element of the target element and replace the target element with the new one by using the replaceChild() method.

Here is an example code snippet:

// select target target 
const targetItem = document.querySelector('li:last-child')

// create a new element
const newItem = document.createElement('li')
newItem.innerHTML = `🍰`

// replace `targetItem` with `newItem`
targetItem.parentNode.replaceChild(newItem, targetItem)

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.