plainJS

Functions / Manipulation

Unwrap a DOM element

jQuery $.unwrap()

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 the parents of an element from the DOM, leaving the element’s content in place.

How to unwrap an element with cross browser safe DOM methods:

js
// select element to unwrap
var el = document.querySelector('div');

// get the element's parent node
var parent = el.parentNode;

// move all children out of the element
while (el.firstChild) parent.insertBefore(el.firstChild, el);

// remove the empty element
parent.removeChild(el);

The code is straight forward and much faster than the corresponding jQuery’s method $.unwrap().