How to replace an element using JavaScript

published: 03 Jul 2022

2 min read

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);

How to replace an element using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming