删除包装div并保留所有子div完整?

时间:2012-02-21 22:47:10

标签: jquery

我有一个包装器div,里面有几个子div,并且这些子div内也有标签。我想删除包装器div。我已经考虑过JQuery的解包,但似乎我需要指定子div来告诉Jquery要解包的内容。如果有几个孩子,这会起作用吗?

所以,代码如下:

<div id="wrapper">
  <div id="innerDiv1"></div>
  <div id="innerDiv2"></div>
  <div id="innerDiv3"></div>
</div>

任何帮助,一如既往,表示赞赏。

谢谢。

4 个答案:

答案 0 :(得分:29)

unwrap方法可以正常工作(您可以选择任意/任意数量的兄弟姐妹):

$("#innerDiv1").unwrap();

从文档(强调添加):

  

匹配的元素(及其兄弟姐妹,如果有的话)取代他们的   DOM结构中的父母。

答案 1 :(得分:5)

添加到@james

你可以做这样的事情

var innerDivs = $("#wrapper").html();
$("#wrapper").remove();
$("body").append(innerDivs);​ // you will need to change this to append to whatever element you like

jsfiddle示例

http://jsfiddle.net/dAZ9D/

答案 2 :(得分:0)

function unwrap(el){
    var parent = el.parentNode; // get the element's parent node
    while (el.firstChild){
        parent.insertBefore(el.firstChild, el); // move all children out of the element
    }
    parent.removeChild(el); // remove the empty element
}

代码是直接的,比相应的jQuery方法$ .unwrap()快得多。

来源:https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/

答案 3 :(得分:0)

另一种解决方案是将.replaceWith().html()结合使用:

jQuery('#wrapper').each(function () {
    var t = jQuery(this);
    t.replaceWith(t.html());
});
相关问题