Hide div's if they are empty

后端 未结 10 1457
不思量自难忘°
不思量自难忘° 2020-12-03 07:21

I have some div\'s that maybe be empty (depending on server-side logic).

相关标签:
10条回答
  • 2020-12-03 08:01
    $('div').each(function() {
    if($(this).html().size() == 0) $(this).remove();
    });
    

    If you want to use the divs later on in the same page, it's better to use $(this).hide(); instead of $(this).remove(); as the divs will be deleted if you use remove();

    0 讨论(0)
  • 2020-12-03 08:04

    Here is a CSS3 solution for anyone who is interested

    div:empty {
      display:none;
    }
    
    0 讨论(0)
  • 2020-12-03 08:05

    jQuery has a :empty selector. So, you can simply do:

    $('div.section:empty').hide();
    
    0 讨论(0)
  • 2020-12-03 08:05

    replace display:block; by display: none;

    edit: Oh, i saw you wanted to use jQuery, then use .hide(): http://api.jquery.com/hide/

    0 讨论(0)
  • 2020-12-03 08:06

    If div contains white-space or line breaks then this code may be helpful...

    $(document).ready(function() {
       str = $('div.section').text();
       if($.trim(str) === "") {
         $('div.section').hide();
       }
    });
    
    0 讨论(0)
  • 2020-12-03 08:08

    Why does nobody use .filter ?

    $("div.section").filter(function() {
        return this.childNodes.length === 0;
    }).hide();
    

    This is a more elegant solution compared to using .each.

    0 讨论(0)
提交回复
热议问题