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.

0

4 Answers 4

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.

1
  • 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. Commented Feb 21, 2012 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/

2
  • 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. Commented Feb 21, 2012 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! Commented Feb 21, 2012 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
  • Can also do like this in latest Jquery as in 2019: $(this).replaceWith($(this).html()); Commented Oct 14, 2019 at 18:38
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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.