jQuery用each方法遍历dom的问题(周末加班解决,在线等~)
本文介绍了jQuery用each方法遍历dom的问题(周末加班解决,在线等~)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
先上示例代码:
html:
<!-- 去除div标签 -->
<section id="test">
<div class="1">
<div class="2">
<img src="http://h.hiphotos.baidu.com/baike/s%3D220/sign=a2c005689058d109c0e3aeb0e159ccd0/a5c27d1ed21b0ef46441fe48dfc451da81cb3e7e.jpg">
</div>
</div>
</section>
js:
$('#test').find('div').each(function(i, e) {
var _this = $(e);
_this.after(_this.html());
_this.remove();
});
执行之后html:
<section id="test">
<div class="2">
<img src="http://h.hiphotos.baidu.com/baike/s%3D220/sign=a2c005689058d109c0e3aeb0e159ccd0/a5c27d1ed21b0ef46441fe48dfc451da81cb3e7e.jpg">
</div>
</section>
问题描述:div.2为什么没有被去除,新插入的标签没有加入到遍历集合里面吗?但是打断点调试的时候看到已经选取到了div.2。如何才能去除嵌套的div标签?
解决方案
https://jsfiddle.net/g7co82nw/
$("#test").find("div").children(":not(div)").appendTo($("#test"));
$("#test").children("div").remove();
这个方法简单,但是可能会造成嵌套关系不正常(比如某个非 div 套了个 div 又套了个非 div 的情况)
可以用一个循环来解决,直到所有 div 都没了
https://jsfiddle.net/g7co82nw/1/
let divs = $("#test").find("div");
while (divs.length) {
divs.children(":not(div)").unwrap();
divs = $("#test").find("div");
}
如果只想移除 #test
的直接子 div,就不用 find()
用 children()
就好
这篇关于jQuery用each方法遍历dom的问题(周末加班解决,在线等~)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文