How can I remove wrapper (parent element) without

2020-02-01 07:16发布

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>

7条回答
别忘想泡老子
2楼-- · 2020-02-01 07:34

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

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-01 07:45

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'));
查看更多
够拽才男人
4楼-- · 2020-02-01 07:46

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

查看更多
够拽才男人
5楼-- · 2020-02-01 07:47

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

查看更多
我想做一个坏孩纸
6楼-- · 2020-02-01 07:55

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();
});
查看更多
地球回转人心会变
7楼-- · 2020-02-01 07:56

if you're using jQuery:

$(".wrapper").replaceWith($(".wrapper").html());
查看更多
登录 后发表回答