views:

292

answers:

3

Hello,

With jQuery I am trying to determine whether or not <div> has content in it or, if it does then I want do nothing, but if doesn't then I want to add display:none to it or .hide(). Below is what I have come up with,

if ($('#left-content:contains("")').length <= 0) { $("#left-content").css({'display':'none'}); }

This does not work at all, if the div has not content then it just shows up anyway, can any offer any advice?

+5  A: 

Just use the :empty filter in your selectors.

$('#left-content:empty').hide();
womp
This doesn't work properly if there are whitespace textnodes inside `#left-content`. Eg `<div id="left-content"> </div>` (that's `" "` inside an otherwise empty div.
Roatin Marth
Yeah, the documentation notes that it's only considered empty if there is no children, including text nodes. That can definitely trip you up.
womp
+2  A: 
if( $( "#left-content" ).html().length == 0 ) {
    $( "#left-content" ).hide();
}
Jacob Relkin
In what case will `html().length` be LESS than 0?
J-P
You are right. Never.
Jacob Relkin
A: 

try to remove first whitespaces:

  // first remove whitespaces

  // html objects content version:
  var content = $.trim($("#left-content).html()).length;

  if(content == 0) {
     $("#left-content).hide();
  }

  // html RAW content version:
  var content = $.trim($("#left-content).html()); // <-- same but without length

  if(content == "") {                             // <-- this == ""
     $("#left-content).hide();
  }
Paco