javascript - 检查特定类的 div 是否包含文本或为空

标签 javascript jquery html dom

我正在尝试检查 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/

相关文章:

javascript - 如何从 Node js 服务器端的表单标签记录数据?

javascript - css 按钮样式无法使用带有 vue.js 的 &lt;style&gt; 标签

javascript - 什么时候需要使用 Object.assign() 方法来复制对象的实例?

HTML - 关于表格单元格宽度

javascript - onclick 删除,html

javascript - Uncaught ReferenceError : Main is not defined with webpack/react in Rails 4. 2.4

javascript - 正则表达式内的阶段 - Javascript

php - 从php获取数据到ajax

jquery序列化()+自定义?

html - 看不到希腊菜单文本和标题段落希腊文本没问题