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

北城余情 提交于 2019-11-28 03:09:01

问题


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

HTML structure:

<div class="wrapper">
  <img src"">
</div>
<div class="button">Remove wrapper</div>

After clicking on the button I would like to have:

<img src"">
<div class="button">Remove wrapper</div>

回答1:


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();
});



回答2:


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'));



回答3:


Surprised that nobody's posting the simplest answer:

// Find your wrapper HTMLElement
var wrapper = document.querySelector('.wrapper');

// Replace the whole wrapper with its own contents
wrapper.outerHTML = wrapper.innerHTML;



回答4:


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




回答5:


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




回答6:


if you're using jQuery:

$(".wrapper").replaceWith($(".wrapper").html());



回答7:


Nowadays it's simpler:

function unwrap (node: Element) {
  node.after(...Array.from(node.childNodes))
  node.remove()
}



回答8:


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



来源:https://stackoverflow.com/questions/19261197/how-can-i-remove-wrapper-parent-element-without-removing-the-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!