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'; = 'new-element';

// 3: replace old element with new one

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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.