确定子div是否包含内容

时间:2018-05-17 20:27:42

标签: javascript jquery html

我正在使用一些允许内容编辑者添加内容的代码。我发现了一些有孩子的div(例如h5p)但没有文字的情况。 div正在占用空间,我想删除所有没有实际文本的div。

我唯一发现的是:empty css选择器,但会检查子项,而不是文本。



$('.col-lg-4:empty').remove();

.col-lg-4 {
  background-color: #c8c8c8;
  margin: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
  <div class="col-lg-4">
    <h5 class="headline1">Test Title</h5>
    <p class="p2"></p>
    <p>This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.</p>
    <p></p>
  </div>
  <div class="col-lg-4">
    <h5 class="subtitle1"></h5>
    <p class="p2"></p>
  </div>
  <div class="col-lg-4">
    <p class="p2 last-column"></p>
  </div>
  <div class="col-lg-4"></div>
</div>
&#13;
&#13;
&#13;

这是我的网站编辑添加的一些真实内容。正如你所看到的,我有不必要的div,没有我想要摆脱的内容(.col-lg-4)。使用:empty,它会移除最后一个没有子项的内容。但是,删除那些没有内容的孩子的最佳方法是什么呢?

2 个答案:

答案 0 :(得分:4)

这就是你想要做的吗?

我无法想到更简单的方法! 检查代码段:

&#13;
&#13;
$('.col-lg-4').each(function() {
  if (!this.innerText)  $(this).remove();
});
&#13;
.col-lg-4 {
  background-color: #c8c8c8;
  margin: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
  <div class="col-lg-4">
    <h5 class="headline1">Test Title</h5>
    <p class="p2"></p>
    <p>This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.</p>
    <p></p>
  </div>
  <div class="col-lg-4">
    <h5 class="subtitle1"></h5>
    <p class="p2"></p>
  </div>
  <div class="col-lg-4">
    <p class="p2 last-column"></p>
  </div>
  <div class="col-lg-4"></div>
</div>
&#13;
&#13;
&#13;

我使用innerText来删除所有的html标签。

希望它有所帮助。

答案 1 :(得分:1)

迭代他们,检查空子,删除:

$('.col-lg-4').each(function () {
  if ($(this).children().text() == '') $(this).remove();
});

没有jQuery:

Array.from(document.querySelectorAll('.col-lg-4'))
  .filter(i => !i.innerText)
  .forEach(e => e.parentNode.removeChild(e));
相关问题