Check if the content of a DIV is empty in jQuery

2019-04-04 16:12发布

How do I use jQuery to check to see if the content of a <div> is empty?

I tried this and is doesn't seem to be printing the correct values.

...
var unframed_items = $("#unframed-items");
alert(unframed_items.html().length);
...
<div id="unframed-items"> </div>
...

标签: jquery html size
3条回答
疯言疯语
2楼-- · 2019-04-04 16:44

Use $('#elementId').is(':empty').

查看更多
孤傲高冷的网名
3楼-- · 2019-04-04 16:45
<div id="portfolio"><!--portfolio-->
<div id="portfolio-works"><!--portfolio-works-->
    <div class="portfolio-works-container"></div>
</div><!--/portfolio-works-->

 $(document).ready(function(){
    if($('div.portfolio-works-container').is(':empty')){
        $('div#portfolio').hide();
    }
});
查看更多
一夜七次
4楼-- · 2019-04-04 16:52

If you mean really empty, use the empty-selector[docs] :

alert( !!$("#unframed-items:empty").length )

or

alert( $("#unframed-items").is(':empty') )

If you consider whitespace-only to be empty, then use the jQuery.trim()[docs] method:

alert( !$.trim( $("#unframed-items").html() ) );
查看更多
登录 后发表回答