I need to hide div when its child element is empty. Specifically, I need to add the class .no-content if the child element is empty.
I have this code with spaces:
<div class="ee-posts-list">
<div class="ee-post "> </div>
<div class="ee-post "> </div>
<div class="ee-post "> </div>
<div class="ee-post "> </div>
</div>
I also need to add a class if the div has no text:
<div class="ee-posts-list">
<div class="ee-post no-content"> </div>
<div class="ee-post no-content"> </div>
<div class="ee-post no-content"> </div>
<div class="ee-post no-content"> </div>
</div>
I have a similar problem that I need to solve, and for that, I use this script:
<script>
document.querySelectorAll('.ee-post').forEach(post => {
if (!post.querySelector('.breakdance').hasChildNodes()) {
post.classList.add('no-content');
}
});
</script>
2
Answers
Use
.innerHTML.trim()
. This will get the contents with surrounding whitespace removed, so it will be empty for the blank divs in your example.This code iterate over all elements with the ee-post class and add a no-content class to any element that has no content:
https://codepen.io/proudhon/pen/OJoNdQd