我想从某些 html 字符串中删除空元素。我知道我可以运行类似的东西:
$('p').each(function(index, item) {
if($.trim($(item).text()) === "") {
$(item).remove();
}
});
问题是我想删除所有空节点 - 不仅仅是 p。另外我希望脚本考虑 <p><span></span></p>
中的 p 节点为空,因为它只包含空元素。你有类似的简单实现吗?
[编辑]
我忘了补充:我可以使用 jQuery,但我想要遍历和编辑的 html 是在一个字符串中 - 而不是实际的文档。那么我该如何进行这个操作呢?我尝试使用 var html = $.parseHTML('<p><span></span></p>')
但每次循环后我仍然得到相同的字符串...
最佳答案
最近我正在寻找同样问题的解决方案。递归函数就是答案。
function removeEmptyTagsRecursively($el) {
if ($el.children().length) {
$el.children().each(function(i, val) {
removeEmptyTagsRecursively($(val));
});
$el.children(':empty').remove();
}
}
关于javascript - 递归地从html中删除空节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581685/