开发者

Remove or hide a div if it's empty

I know this should be simple but can't figure it out. Here's the code.

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

I simply need to remove the "leftMenuWrapper" if "leftmenu" is empty. Here's what I've been using.

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

Sorry if thi开发者_C百科s is a simple question. Having a Monday!

Thanks!


You can do it like this:

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

This only selects #leftmenu if it's :empty, and then only grabs the .parent() of that to .remove(). If it wasn't empty, then the first selector won't find anything, or any parent to remove either.


If you want to remove if it looks empty:

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

jsFiddle example

The above takes just the text contents of #leftmenu and trims off the whitespace before checking if anything's there.

The big advantage of the above over $(#leftmenu:empty) is that the above removes in the following cases where :empty would not:

                  // 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()


Note that the following is more efficient (but less readable imo):

var $elie = ('#leftmenu');
if ( $.trim( $elie.text() ) == "")
    $elie.parent().remove();


if(!$('#leftmenu').html()){ $('#leftmenu').parent().remove(); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜