How to remove a shell (parent) without deleting a child?

I would like to remove the parent without removing the child - is this possible?

HTML structure:

<div class="wrapper"> <img src""> </div> <div class="button">Remove wrapper</div> 

After clicking on the button, I would like to have:

 <img src""> <div class="button">Remove wrapper</div> 
+12
source share
8 answers

You can use this API: http://api.jquery.com/unwrap/

Demo http://jsfiddle.net/7GrbM/

.unwrap

The code will look something like this:

Code example

 $('.button').click(function(){ $('.wrapper img').unwrap(); }); 
+11
source

A pure JS solution that does not use innerHTML:

 function unwrap(wrapper) { // place childNodes in document fragment var docFrag = document.createDocumentFragment(); while (wrapper.firstChild) { var child = wrapper.removeChild(wrapper.firstChild); docFrag.appendChild(child); } // replace wrapper with document fragment wrapper.parentNode.replaceChild(docFrag, wrapper); } 

Try :

 unwrap(document.querySelector('.wrapper')); 
+25
source

Surprised that no one posted the simplest answer:

 // Find your wrapper HTMLElement var wrapper = document.querySelector('.wrapper'); // Replace the whole wrapper with its own contents wrapper.outerHTML = wrapper.innerHTML; 
+10
source

The Pure JS (ES6) solution, in my opinion, is easier to read than jQuery solutions.

 function unwrap(node) { node.replaceWith(...node.childNodes); } 

node must be ElementNode

+10
source

A clean javascript solution, I'm sure someone can simplify it, but this is an alternative for pure javascript guys.

HTML

 <div class="button" onclick="unwrap(this)">Remove wrapper</div> 

Javascript (clean)

 function unwrap(i) { var wrapper = i.parentNode.getElementsByClassName('wrapper')[0]; // return if wrapper already been unwrapped if (typeof wrapper === 'undefined') return false; // remmove the wrapper from img i.parentNode.innerHTML = wrapper.innerHTML + i.outerHTML; return true; } 

JSFIDDLE

+5
source

if you use jQuery:

 $(".wrapper").replaceWith($(".wrapper").html()); 
+1
source

This is currently easier:

 function unwrap (node: Element) { node.after(...Array.from(node.childNodes)) node.remove() } 
0
source

If the shell element contains text, the text remains with the child nodes.

-2
source

Source: https://habr.com/ru/post/955541/


All Articles