Pure Javascript - Replacing an Element

Use-Cases of this Tutorial

  • You are looking to know how to replace an element using Javascript.
  • You are looking to know the pure Javascript version of the jQuery function "replaceWith"

Method 1 — Using replaceChild

The replaceChild method replaces one child node of a parent element with another element.

<div id="one">
	<div id="two">Two</div>
</div>
var old_element = document.querySelector('#two');

// get the parent
var parent = old_element.parentNode;

var new_element = document.createElement('span');
new_element.innerHTML = 'Two Edited';

// replace child of the parent
parent.replaceChild(new_element, old_element);

// result
// <div id="one"><span>Two Edited</span></div>

replaceChild is available since IE6 times, so is very well supported by all browsers.

Method 2 — Using replaceWith

The replaceWith method replaces a node with another node. This method is better than replaceChild because :

  1. There is no need to find the parent element.
  2. It also accepts a DOMString (a html string), so there is no need to create a new element. However bear in mind that using a DOMString will result in creation of a Text node - it will be considered as the inside text.

This method is basically like replaceWith in jQuery.

<div id="one">
	<div id="two">Two</div>
</div>
var old_element = document.querySelector('#two');

var new_element = document.createElement('span');
new_element.innerHTML = 'Two Edited';

old_element.replaceWith(new_element);

// result
// <div id="one"><span>Two Edited</span></div>

replaceWith is fairly new, so not all browsers support it. However it is only a matter of time before this method becomes mainstream. There is also a polyfill available in case replaceWith is not natively available.

Writing jQuery find() in Pure Javascript
Writing jQuery closest() in Pure Javascript