Mike S. Rosekrans
Mike S. Rosekrans

Reputation: 3

Hide parent div if an child divs are empty

I have this three column row and would like to hide the two empty columns.

<div class="wp-block-columns">
   <div class="wp-block-column">
      <div class="wp-block-image">content</div>
      <div class="tb-field">content</div>
      <div class="tb-field">content</div>
      <div class="tb-button>content</div>
   </div>
   
   <div class="wp-block-column">
      <div class="wp-block-image"> </div>
      <div class="tb-field"> </div>
      <div class="tb-field"> </div>
      <div class="tb-button> </div>
   </div>

   <div class="wp-block-column">
      <div class="wp-block-image"> </div>
      <div class="tb-field"> </div>
      <div class="tb-field"> </div>
      <div class="tb-button> </div>
   </div>

</div>

I tried this and a few other variations without any luck.

jQuery('.wp-block-column') // find the parent
.hide() // hide it
.find('> div:not(:empty)') // find child divs that are not empty
.each(function() { // use each in order to prevent errors when set is empty

jQuery(this).parent().show(); // show the parent of this non-empty element
return false; // stop processing this each
})
    ;

Upvotes: 0

Views: 131

Answers (3)

Phil F
Phil F

Reputation: 702

I was not able to follow how your code is not working as you wanted. I only noticed that I had to fix the html for the div.tb-button tag. It needed the closing double quote.

Having said that, why not try testing against the trimmed version of the text to see if it's empty. It would transverse the DOM a lot less and be quicker with less code to manage.

jQuery('.wp-block-column').each(function () {
    var $this = jQuery(this);
    $this.text().trim() === '' && $this.remove();
});

You can replace "remove" (removing the element from the DOM) with "hide" (display: "none" on the element), if you prefer.

Upvotes: 1

BeldrNL
BeldrNL

Reputation: 53

I should do:

function checkIfEmpty(parentid, childid){ if (document.getElementById(childid).innerHTML == "") { document.getElementById(parentid).style.display = 'none'; } }

I hope this is what you are looking for

Upvotes: 0

Danil Rusakov
Danil Rusakov

Reputation: 76

Try this.

jQuery('.wp-block-column').each(function(){
  var current_column = jQuery(this);
  var image = current_column.find('.wp-block-image');
  var field = current_column.find('.tb-field');
  var button = current_column.find('.tb-button');
  
  if(jQuery.trim(image.html()) == 0){
    current_column.hide();
  }
  if(jQuery.trim(field.html()) == 0){
    current_column.hide();
  }
  if(jQuery.trim(button.html()) == 0){
    current_column.hide();
  }
});

Upvotes: 0

Related Questions