如何使用jQuery删除所有内部custom_blank均为空的custompsps类div
实现代码
$('.custompsps').each(function() { const $currentPsps = $(this); // 获取当前容器下所有.custom_blank元素 const $allBlanks = $currentPsps.find('.custom_blank'); // 判定所有custom_blank是否均为空白(自动过滤空格、换行等空白字符) const allBlankEmpty = $allBlanks.toArray().every(item => { return $(item).text().trim() === '' }); // 全部为空时删除当前容器 if (allBlankEmpty) { $currentPsps.remove(); } });
逻辑说明
- 无需手动编写两层循环,直接用
find方法即可获取当前.custompsps容器内所有层级的.custom_blank元素 - 数组
every方法只要存在一个不符合判定条件的元素就会返回false,刚好匹配需求:只要有一个.custom_blank有内容,当前容器就保留 - 如果你定义的「空」是元素内完全没有任何内容(空格、换行也算非空),可以把判断条件替换为:
const allBlankEmpty = $allBlanks.toArray().every(item => $(item).is(':empty'));
内容的提问来源于stack exchange,提问作者Sunny
相关产品推荐
相关产品推荐

