我正在尝试检查 jQuery 中某个特定类的元素是否包含某些文本。如果它不包含任何文本,那么我想删除该类。
<div class="description">
</div>
最佳答案
使用:empty
$('.description:empty').removeClass('description');
根据文档
Select all elements that have no children (including text nodes).
console.log($('.description:empty').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="description"></div>
但是,如果问题中的 HTML 格式不正确(不必要的空格),您将不得不采取更手动的方法
if ($(this).children().length == 0 && $(this).text().trim() == '')
$('.description').each(function() {
if ($(this).children().length == 0 && $(this).text().trim() == '') {
console.log('entered');
$(this).removeClass('description');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="description">
</div>
关于javascript - 检查特定类的 div 是否包含文本或为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31085619/