skip to Main Content

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


  1. Use .innerHTML.trim(). This will get the contents with surrounding whitespace removed, so it will be empty for the blank divs in your example.

    document.querySelectorAll('.ee-post').forEach(post => {
      if (post.querySelector('.breakdance').innerHTML.trim() == '') {
        post.classList.add('no-content');
      }
    });
    
    Login or Signup to reply.
  2. This code iterate over all elements with the ee-post class and add a no-content class to any element that has no content:

    document.querySelectorAll('.ee-post').forEach(function(element) {
        if (element.innerHTML.trim() === '') {
            element.classList.add('no-content');
            console.log("class added");
        }
    });
    

    https://codepen.io/proudhon/pen/OJoNdQd

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search