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

后端 未结 7 1239
天命终不由人
天命终不由人 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: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'));
    

提交回复
热议问题