How can I remove wrapper (parent element) without removing the child?

后端 未结 7 1224
天命终不由人
天命终不由人 2020-12-03 20:48

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

HTML structure:

相关标签:
7条回答
  • 2020-12-03 21:22

    Could use this API: http://api.jquery.com/unwrap/

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

    .unwrap

    Code will look something on these lines:

    Sample Code

    $('.button').click(function(){
        $('.wrapper img').unwrap();
    });
    
    0 讨论(0)
  • 2020-12-03 21:23

    Pure JS solution that doesn't 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 it:

    unwrap(document.querySelector('.wrapper'));
    
    0 讨论(0)
  • 2020-12-03 21:30

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

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

    node has to be an ElementNode

    0 讨论(0)
  • 2020-12-03 21:32

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

    0 讨论(0)
  • 2020-12-03 21:33

    if you're using jQuery:

    $(".wrapper").replaceWith($(".wrapper").html());
    
    0 讨论(0)
  • 2020-12-03 21:35

    Pure javascript solution, i'm sure someone can simplify it more but this is an alternative for pure javascript guys.

    HTML

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

    Javascript (pure)

    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

    0 讨论(0)
提交回复
热议问题