gpt4 book ai didi

javascript - 确定子 div 是否有内容

转载 作者:行者123 更新时间:2023-11-28 05:13:36 25 4
gpt4 key购买 nike

我正在使用一些允许内容编辑器添加内容的代码。我发现了一些实例,其中有一个 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>

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

最佳答案

这是你想做的吗?

我想不出更简单的方法!
检查片段:

$('.col-lg-4').each(function() {
if (!this.innerText) $(this).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>

我使用 innerText 去除了所有的 html 标签。

希望对您有所帮助。

关于javascript - 确定子 div 是否有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50400015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com