How To Replace Element Javascript

Replacing an HTML element with another element can be accomplished using JavaScript. In this tutorial, we will discuss two different methods to replace an element using JavaScript: the replaceChild() method and the replaceWith() method.

Method 1: Using replaceChild()

The replaceChild() method is a built-in JavaScript method that can be used to replace an existing element with a new element. It requires two arguments: the new element and the element to be replaced. The syntax for using the replaceChild() method is as follows:

parentNode.replaceChild(newElement, oldElement);

To demonstrate this method, let’s use the following HTML code:

<div id="container">
  <h2 id="title">Old Title</h2>
</div>

We will replace the <h2> element with a new <h3> element:

var container = document.getElementById('container');
var oldTitle = document.getElementById('title');

var newTitle = document.createElement('h3');
newTitle.innerHTML = 'New Title';

container.replaceChild(newTitle, oldTitle);

The above code will replace the <h2> element with the new <h3> element, resulting in the following HTML:

<div id="container">
  <h3>New Title</h3>
</div>

Method 2: Using replaceWith()

The replaceWith() method is another built-in JavaScript method that can be used to replace an existing element with a new element. Unlike the replaceChild() method, the replaceWith() method is called directly on the element to be replaced. The syntax for using the replaceWith() method is as follows:

oldElement.replaceWith(newElement);

Using the same HTML code as in the previous example:

<div id="container">
  <h2 id="title">Old Title</h2>
</div>

We can replace the <h2> element with a new <h3> element using the replaceWith() method:

var oldTitle = document.getElementById('title');

var newTitle = document.createElement('h3');
newTitle.innerHTML = 'New Title';

oldTitle.replaceWith(newTitle);

The above code will also replace the <h2> element with the new <h3> element, resulting in the following HTML:

<div id="container">
  <h3>New Title</h3>
</div>

Conclusion

In this tutorial, we have explored two different methods for replacing an element in JavaScript: the replaceChild() method and the replaceWith() method. Both methods are effective and can be used based on your specific requirements and browser compatibility considerations.