tags:

views:

80

answers:

3

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 this is a simple question. Having a Monday!

Thanks!

+11  A: 

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.

Nick Craver
Who said scripting wasn't elegant?
Ryan Ternier
+1 for showing me the `:empty` selector.
Peter Ajtai
@Peter - I think next to `:animated` and `:header` it's the most under-utilized of the really handy pseudo-selectors out there, give them some love!
Nick Craver
+1  A: 
if(!$('#leftmenu').html()){ $('#leftmenu').parent().remove(); }
Senica Gonzalez
This would seem to work, but it is not quite as efficient because you're having to select the element twice. Certainly seems like a valid solution, though.
patrick dw
@patrick - I guess you could do `var $elie = $('#leftmenu'); if(!$elie.html()){ $elie.parent().remove(); }`
Peter Ajtai
@Peter - Very true. Would be much better to cache the result of the selector. In fact, for an element with an ID that gets selected more than once anywhere, I'd probably cache it.
patrick dw
+2  A: 

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();
Peter Ajtai
+1 - I'll bet a lot of people get stuck when `:empty` doesn't work because there a space or line break.
patrick dw