# How to replace an element using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 9, 2020, updated Oct 23, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-replace-an-element

> Learn how to replace a DOM element by using the replaceChild() method in 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:

```html
<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](https://attacomsian.com/blog/getting-dom-elements-javascript) that you want to replace.
2. [Create a new DOM element](https://attacomsian.com/blog/javascript-create-dom-element) with all the content you need.
3. [Select the parent element](https://attacomsian.com/blog/javascript-dom-get-the-parent-of-an-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:

```javascript
// 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)
```
