22

I have one wrapper div with several sub-divs inside and tags inside those sub-divs as well. I want to remove the wrapper div. I have considered JQuery's unwrap, but it appears as though I need to specify the child divs to tell Jquery what to unwrap. Will this work if there are several children?

So, the code looks like:

<div id="wrapper">
  <div id="innerDiv1"></div>
  <div id="innerDiv2"></div>
  <div id="innerDiv3"></div>
</div>

Any help, as always, is appreciated.

Thank you.

robert smith
  • 861
  • 2
  • 10
  • 17

4 Answers4

37

The unwrap method will work fine (you can select any of/any number of the siblings):

$("#innerDiv1").unwrap();

From the docs (emphasis added):

The matched elements (and their siblings, if any) replace their parents within the DOM structure.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    Thanks @James Allardice. Even though I checked the JQuery docs, I somehow missed the "and their siblings" part. Getting a little bleary eyed I guess. – robert smith Feb 21 '12 at 23:03
7

To add on to @james

You can do something like this

var innerDivs = $("#wrapper").html();
$("#wrapper").remove();
$("body").append(innerDivs);​ // you will need to change this to append to whatever element you like

jsfiddle example

http://jsfiddle.net/dAZ9D/

Jaspreet Chahal
  • 2,759
  • 1
  • 15
  • 17
  • 3
    You could do this, but you would lose any event handlers bound to the children of `#wrapper` because the elements are removed from the DOM completely and then added again. Using the `unwrap` method will preserve those event handlers as elements are never removed from the DOM. – James Allardice Feb 21 '12 at 22:54
  • yes thats right james but he doesn't specificly asked whether to maintain even handler or not. Thats why I said to "add on to James answer" :) Cheers! – Jaspreet Chahal Feb 21 '12 at 22:55
5

Another solution would be to use .replaceWith() in conjunction with .html():

jQuery('#wrapper').each(function () {
    var t = jQuery(this);
    t.replaceWith(t.html());
});
1
function unwrap(el){
    var parent = el.parentNode; // get the element's parent node
    while (el.firstChild){
        parent.insertBefore(el.firstChild, el); // move all children out of the element
    }
    parent.removeChild(el); // remove the empty element
}

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

Source: https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50