我需要帮助从div内容中删除特定的div。
我有这样的html内容:
<div class="wrapper">
<div class="list">
<div class="item">
<div class="icon"></div>
<div class="container">html content</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>html</div>
<div>html</div>
<div>html</div>
</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>text</div>
<div class="image-icon">
<img src="test.png">
</div>
</div>
</div>
</div>
</div>
我该怎么做:
<div class="container">html content</div>
<div class="container">
<div>html</div>
<div>html</div>
<div>html</div>
</div>
<div class="container">
<div>text</div>
<img src="test.png">
</div>
我需要删除:
<div class="wrapper"></div>
<div class="list"></div>
<div class="item"></div>
<div class="icon"></div>
<div class="image-icon"></div>
这是我的代码:
$("#save").click(function() {
var data = $(".list").html();
// $(".wrapper").find(".list, .item, .icon, .image-icon").remove();
// $.post('save.php', {
// contents: data
// });
alert(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="list">
<div class="item">
<div class="icon"></div>
<div class="container">html content</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>html</div>
<div>html</div>
<div>html</div>
</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>text</div>
<div class="image-icon">
<img src="test.png">
</div>
</div>
</div>
</div>
</div>
<input type="button" id="save" value="SAVE" />
答案 0 :(得分:3)
您可以使用unwrap()
删除包装的元素,也可以使用remove()
的方法删除空白元素,使用:empty
pseudo-class selector获取空白元素。
// get all elements you want to remove
$('.wrapper,.list,.item,.icon,.image-icon')
// filter out empty elements and remove
.filter(':empty').remove()
// back to the main selector
.end()
// get it's children elements(including textnode, commetnode... elements)
.contents()
// unwrap elements(will remove it's parent)
.unwrap()
var $main = $('#main');
$main.find('.wrapper,.list,.item,.icon,.image-icon')
.filter(':empty').remove()
.end()
.contents()
.unwrap();
console.log($main.html().trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div class="wrapper">
<div class="list">
<div class="item">
<div class="icon"></div>
<div class="container">html content</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>html</div>
<div>html</div>
<div>html</div>
</div>
</div>
<div class="item">
<div class="icon"></div>
<div class="container">
<div>text</div>
<div class="image-icon"><img src="test.png"></div>
</div>
</div>
</div>
</div>
</div>