johnny 5 johnny 5 - 5 months ago 55
Javascript Question

jQuery unwrap is not working

I'm trying to use unwrap to remove an parent element. I'm following the documentation and yet it doesn't work; I have Html Like this:

test html


and I wrote this function to clone and unwrap it:

var htmlTemplate = $('#htmlTemplate').clone().removeAttr('id').unwrap();


When I run this code the template still has the outer span on it.
Does anyone know how to unwrap this properly?

Answer

To unwrap an element it should have a parent. You are creating a DOM fragment and trying to unwrap it. But it has no parents.

Say, there's some dom:

<button>unwrap</button>
<div class="outer"></div>

With the parent in place unwraping goes just fine:

var inner = '<span class="inner">test html</span>',
        $outer = $('.outer');

// First you would want your element to get a parent.
$outer.html(inner);


// Then unwrap it
$('button').on('click', function() {
    $('.inner').unwrap();
});

here's the fiddle

So, if you want to remove the outer span, you should target the inner one and it will unwrap.

For the updated fragment: .clone() doesn't copy any parents it copies only the element and all it's descendants. So when you use clone - you build a separate fragment with root at the selected element.

.unwrap() removes the parent(s) of the matched element(s). So to unwrap the inner span you must select it with jQuery.

<div class="outer"></div>

js

var html = "<span><span class='inner'>test html </span></span>";

var $html = $(html);

var unwraped = $html.find('.inner').unwrap();

$('.outer').html(unwraped);

another fiddle