Using an if statement to check if a div is empty

前端 未结 10 1057
忘了有多久
忘了有多久 2020-11-28 03:20

I\'m trying to remove a specific div if a separate div is empty. Here\'s what I\'m using:

$(document).ready(function () {
    if (\'#leftmenu:empty\') {
             


        
相关标签:
10条回答
  • 2020-11-28 03:20

    You can use .is().

    if( $('#leftmenu').is(':empty') ) {
        // ...
    

    Or you could just test the length property to see if one was found.

    if( $('#leftmenu:empty').length ) {
        // ...
    

    Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim() and check for the length of the content.

    if( !$.trim( $('#leftmenu').html() ).length ) {
        // ...
    
    0 讨论(0)
  • 2020-11-28 03:21

    You can extend jQuery functionality like this :

    Extend :

    (function($){
        jQuery.fn.checkEmpty = function() {
           return !$.trim(this.html()).length;
        };
    }(jQuery));
    

    Use :

    <div id="selector"></div>
    
    if($("#selector").checkEmpty()){
         console.log("Empty");
    }else{
         console.log("Not Empty");
    }
    
    0 讨论(0)
  • 2020-11-28 03:21
    if (typeof($('#container .prateleira')[0]) === 'undefined') {
        $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
    }
    
    0 讨论(0)
  • 2020-11-28 03:25

    also you can use this :

    
        if (! $('#leftmenu').children().length > 0 ) {
             // do something : e.x : remove a specific div
        }
    

    I think it'll work for you !

    0 讨论(0)
  • 2020-11-28 03:28

    In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:

    $('[name="_invisibleIfEmpty"]').filter(function () {
        return $.trim($(this).html()).length == 0;
    }).hide();
    

    or .remove() rather than .hide(), whatever you prefer.

    FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".

    0 讨论(0)
  • 2020-11-28 03:29
    if($('#leftmenu').val() == "") {
       // statement
    }
    
    0 讨论(0)
提交回复
热议问题