How to replace an element using JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.