简体   繁体   English

如何在不删除子级的情况下删除包装器(父元素)?

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

I would like to remove the parent without removing the child - is this possible? 我想删除父母而不删除孩子-这可能吗?

HTML structure: HTML结构:

<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>

Pure JS solution that doesn't use innerHTML: 不使用innerHTML的纯JS解决方案:

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

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;

Pure JS (ES6) solution, in my opinion easier to read than jQuery-solutions. 我认为,纯JS(ES6)解决方案比jQuery解决方案更易于阅读。

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

node has to be an ElementNode 节点必须是ElementNode

Could use this API: http://api.jquery.com/unwrap/ 可以使用以下API: http : //api.jquery.com/unwrap/

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

.unwrap

Code will look something on these lines: 代码将在以下几行中显示:

Sample Code 样例代码

$('.button').click(function(){
    $('.wrapper img').unwrap();
});

Pure javascript solution, i'm sure someone can simplify it more but this is an alternative for pure javascript guys. 纯JavaScript解决方案,我敢肯定有人可以进一步简化它,但这是纯JavaScript专家的替代选择。

HTML 的HTML

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

Javascript (pure) Javascript(纯)

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 JSFIDDLE

如果您使用的是jQuery:

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

如果wrapper元素包含文本,则文本保留有子节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM