plainJS

Functions / Manipulation

Replace a DOM element

jQuery $.replaceAll(), $.replaceWith()

2015 page

This is the original page from 2015, kept at its address while the tested rewrite is in progress. The code is of its time: it ran in Internet Explorer and does not use what browsers have gained since. The rewrite replaces it here.

In short

Remove an element from the DOM tree and insert a new one in its place.

Replacing one element with another by use of the cross-browser safe DOM method replaceChild():

js
// select the element that will be replaced
var el = document.querySelector('div');

// create a new element that will take the place of "el"
var newEl = document.createElement('p');
newEl.innerHTML = '<b>Hello World!</b>';

// replace el with newEL
el.parentNode.replaceChild(newEl, el);

Find other examples about the replaceChild() method on w3schools.