如果嵌套div为空,则隐藏父Div

时间:2016-10-07 23:35:53

标签: javascript jquery

当嵌套div为空(包括空白节点)时,我试图隐藏外部div。我找到了一个解决方案,如果没有空格,它可以工作: Hide parent DIV if <li> is Empty

当存在空白区域时,我需要它才能工作,即:

 
  <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

3 个答案:

答案 0 :(得分:2)

<强> Working fiddle

您可以同时使用:empty:contain()选择器:

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

希望这有帮助。

$("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>

答案 1 :(得分:1)

您可以迭代每个div.product并修剪文本以删除空格。如果剩下任何东西,请显示它,否则,隐藏它的包装。

$("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>

答案 2 :(得分:0)

//使用Jquery

尝试此操作
<script>

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

</script>