如何移除包含空子元素但无实际文本的.col-lg-4 div?
解决方法:移除包含空元素但无实际文本的容器
嘿,这个问题我之前也碰到过!:empty选择器确实有局限性——它只会匹配**完全没有任何子节点(包括文本节点)**的元素,而你的.col-lg-4容器里虽然有子元素,但这些子元素全是空的,所以:empty根本不会选中它们。
我们需要换个思路:检查容器内的实际文本内容是否有效(也就是去掉所有空白字符后是否为空)。下面是具体的实现方案:
方案1:使用jQuery实现
遍历所有.col-lg-4元素,通过text()获取容器内所有文本内容,用$.trim()去除首尾空白后判断长度,如果长度为0说明没有实际文本,直接移除该容器:
$(document).ready(function() { $('.col-lg-4').each(function() { // 去除所有空白字符后判断是否为空 if ($.trim($(this).text()).length === 0) { $(this).remove(); } }); });
方案2:原生JavaScript实现
如果你不想依赖jQuery,用原生JS也能轻松实现,逻辑和上面一致:
document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('.col-lg-4').forEach(function(el) { if (el.textContent.trim().length === 0) { el.remove(); } }); });
完整测试代码
把上面的代码整合到你的示例中,最终效果如下(只有第一个有实际文本的容器会保留):
<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> <style> .col-lg-4 { background-color: #c8c8c8; margin: 10px; } </style> <script> // 这里可以替换成上面的jQuery或原生JS代码 $(document).ready(function() { $('.col-lg-4').each(function() { if ($.trim($(this).text()).length === 0) { $(this).remove(); } }); }); </script>
这个方法会帮你精准移除那些看起来有子元素,但实际上没有任何有效文本内容的容器,完美解决你的问题!
内容的提问来源于stack exchange,提问作者Hunter Turner
相关产品推荐
相关产品推荐

