Reputation: 6894
I'm working with some code that allows content editors to add content. I've found a few instances where there is a div that has children (like h5
or p
) but no text. The div is taking up space and I would like to remove all of the divs that have no actual text in it.
The only thing I've found is the :empty
css selector, but that checks for children, not text.
$('.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>
This is some real content from my site that editors have added. As you can see, I have unnecessary divs with no content (the .col-lg-4
ones) that I would like to get rid of. With the :empty
, it removes the last one that has no children. But what would be the best way to remove the ones that have children that have no content?
Upvotes: 1
Views: 187
Reputation: 10081
Is that what you want to do?
I can't think of an easier way to do it!
Check the snippet:
$('.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>
I used innerText
to get rid of all the html tags.
Hope it helps.
Upvotes: 3
Reputation:
Iterate over them, check for empty children, remove:
$('.col-lg-4').each(function () {
if ($(this).children().text() == '') $(this).remove();
});
Without jQuery:
Array.from(document.querySelectorAll('.col-lg-4'))
.filter(i => !i.innerText)
.forEach(e => e.parentNode.removeChild(e));
Upvotes: 1