caseyz
caseyz

Reputation: 53

Hide Parent Div if nested div is empty

I'm trying to hide the outer div when a nested div is empty (including white-space node). I've found a solution that works if there is NO whitespace: Hide parent DIV if <li> is Empty

I need it to work when there IS white space present, ie:

  <div class="gen-customer">
    <div class="wrapper">
      <div class="heading">Hidden if working 1</div>
       <div class="content">
      <div class="product"> </div>
    </div>
   </div>
 </div>

Example fiddle

Upvotes: 5

Views: 2152

Answers (3)

sideroxylon
sideroxylon

Reputation: 4416

You can iterate over each div.product and trim the text to remove whitespace. If there's anything left, show it, otherwise, hide its wrapper.

$("div.product").each(function() {
  if ($(this).text().trim() == '') {
    $(this).closest('div.wrapper').hide()
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Hidden if working 1</div>
    <div class="content">
      <div class="product"></div>
    </div>
  </div>
</div>

<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Visible if working 2</div>
    <div class="content">
      <div class="product">text</div>
    </div>
  </div>
</div>

<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Hidden if working 3</div>
    <div class="content">
      <div class="product"></div>
    </div>
  </div>
</div>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle

You could use the both :empty and :contain() selector :

$("div.product:contains(' '), div.product:empty").closest('div.wrapper').hide();

Hope this helps.

$("div.product:contains(' '), div.product:empty").closest('div.wrapper').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Hidden if working 1</div>
    <div class="content">
      <div class="product"> </div>
    </div>
  </div>
</div>

<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Visible if working 2</div>
    <div class="content">
      <div class="product">text</div>
    </div>
  </div>
</div>

<div class="gen-customer">
  <div class="wrapper">
    <div class="heading">Hidden if working 3</div>
    <div class="content">
      <div class="product"></div>
    </div>
  </div>
</div>

Upvotes: 3

Dennisrec
Dennisrec

Reputation: 333

//Try this using Jquery

<script>

    //A perfect reference in Jquery...
    var element=$('#target_child');
    if($(element).html()==''){
        $(element).parent().hide()
    }else{
        //do some work
    }

</script>

Upvotes: 0

Related Questions