Delete or hide the div if it is empty

I know that this should be simple, but cannot understand. Here is the code.

<div class="cols lmenu_item1" id="leftMenuWrapper">
<div id="leftmenu"></div>
</div>

I just need to remove "leftMenuWrapper" if "leftmenu" is empty. Here is what I used.

$('#leftmenu').empty().remove('#leftMenuWrapper');

Sorry if this is a simple question. Monday!

Thank!

+5
source share
3 answers

You can do it as follows:

$('#leftmenu:empty').parent().remove();

It picks #leftmenuif it is :empty, and then captures .parent()from .remove(). If it was not empty, then the first selector will not find anything, or any parent to delete.

+23
source

If you want to delete if it looks empty:

if ( $.trim( $('#leftmenu').text() ) == "")
    $('#leftMenuWrapper').remove();

JsFiddle example

#leftmenu , - .

$(#leftmenu:empty) , , :empty :

                  // The above code works in these cases where ":empty" does not:

<div id="leftmenu">     </div>                              // <== white space
<div id="leftmenu"><p></p></div>                            // <== empty elements

. trim()
. text()
. remove()


, ( imo):

var $elie = ('#leftmenu');
if ( $.trim( $elie.text() ) == "")
    $elie.parent().remove();
+5
if(!$('#leftmenu').html()){ $('#leftmenu').parent().remove(); }
+1
source

All Articles