显示div元素是否具有内容

时间:2022-08-24 16:24:52

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,

使用jQuery我试图确定

是否有内容,或者如果它确实那么我想什么都不做,但如果没有,那么我想添加display:none或者.hide()。以下是我的想法,

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

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?

这根本不起作用,如果div没有内容,那么无论如何它只是出现,可以提供任何建议吗?

3 个解决方案

#1


7  

Just use the :empty filter in your selectors.

只需在选择器中使用:empty过滤器即可。

$('#left-content:empty').hide();

#2


4  

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

#3


0  

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();
  }

#1


7  

Just use the :empty filter in your selectors.

只需在选择器中使用:empty过滤器即可。

$('#left-content:empty').hide();

#2


4  

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

#3


0  

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();
  }