Search code examples
jqueryhtmlunwrap

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?


Solution

  • 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

    Upd:

    There's difference between traversing the DOM and modifying it. When you use .find() - you are traversing (moving from element to element). The structure of the DOM tree stays the same. When you use .unwrap() - you are altering the structure (removing an element from the DOM).