jQuery 删除包装 div 并保持所有子 div 完好无损?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9386544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove wrapping div and leave all sub-divs intact?
提问by robert smith
I have one wrapper div with several sub-divs inside and tags inside those sub-divs as well. I want to remove the wrapper div. I have considered JQuery's unwrap, but it appears as though I need to specify the child divs to tell Jquery what to unwrap. Will this work if there are several children?
我有一个包装器 div,里面有几个子 div,这些子 div 中还有标签。我想删除包装 div。我已经考虑过 JQuery 的解包,但看起来好像我需要指定子 div 来告诉 Jquery 解包什么。如果有几个孩子,这行得通吗?
So, the code looks like:
所以,代码看起来像:
<div id="wrapper">
<div id="innerDiv1"></div>
<div id="innerDiv2"></div>
<div id="innerDiv3"></div>
</div>
Any help, as always, is appreciated.
一如既往,任何帮助表示赞赏。
Thank you.
谢谢你。
回答by James Allardice
The unwrap
method will work fine (you can select any of/any number of the siblings):
该unwrap
方法可以正常工作(您可以选择任何/任意数量的兄弟姐妹):
$("#innerDiv1").unwrap();
From the docs (emphasis added):
从文档(强调添加):
The matched elements (and their siblings, if any) replace their parents within the DOM structure.
匹配的元素(以及它们的兄弟元素,如果有的话)在 DOM 结构中替换它们的父元素。
回答by Jaspreet Chahal
To add on to @james
添加到@james
You can do something like this
你可以做这样的事情
var innerDivs = $("#wrapper").html();
$("#wrapper").remove();
$("body").append(innerDivs);? // you will need to change this to append to whatever element you like
jsfiddle example
jsfiddle 示例
回答by Jens Svalgaard
Another solution would be to use .replaceWith()
in conjunction with .html()
:
另一种解决方案是.replaceWith()
结合使用.html()
:
jQuery('#wrapper').each(function () {
var t = jQuery(this);
t.replaceWith(t.html());
});
回答by Glen Pierce
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
}
The code is straight forward and much faster than the corresponding jQuery's method $.unwrap().
代码很直接,比相应的 jQuery 方法 $.unwrap() 快得多。
Source: https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
来源:https: //plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/