How to Replace an HTML Element With Another Element?

Using JavaScript, you can replace an HTML element with another element in the following way:

  1. Select the element you wish to replace;
  2. Create the new element you wish to replace the old one with;
  3. Use the Element.replaceWith() method to replace the old element with the new one.

For example, consider the following, which demonstrates this:

<div id="old-element">foo</div>
// 1: select element you wish to replace
const oldElem = document.getElementById('old-element');
// 2: create new element to replace old one with
const newElem = document.createElement('h1');
newElem.textContent = 'foobar';
newElem.id = 'new-element';

// 3: replace old element with new one
oldElem.replaceWith(newElem);

This code will replace the old element with the new element in the DOM, resulting in an <h2> HTML element with "foobar" as its text, and "new-element" as its id.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.