jQuery:如果所有子div的html为空,则隐藏父div

我有一个包含三个子div的父div,我想检查子div以查看它们是否为空,如果它们都是空的,我想隐藏父div,以便背景在我的设计中消失。

test
jQuery(".tot1:empty, .tot2:empty, .tot3:empty").parent().hide();

其他答案很好,但出于性能原因,我推荐这个:

 $('.main').each(function () { var $main = $(this), $allChildren = $main.children(); $allEmptyChildren = $allChildren.filter(':empty'); $main.toggle($allChildren.length !== $allEmptyChildren.length); }); 
  • 即使页面中有多个.main元素,它也能正常工作。
  • 它缓存$(this)的值并重用查询结果以提高性能。
  • 它不会hide() .mainshow()它(以避免重绘)。
  • 它不需要父节点上的任何额外标记。
  • 即使您以后决定将子节点从

    更改为更具语义的东西,它也能工作。

  • 当所有孩子都空着时,它不仅会隐藏.main ,它会在孩子有文字时显示它们。 所以它处理隐藏和显示。 您所要做的就是再次运行它。

源代码非常明确:它找到所有直接的孩子。 然后找到空的。 如果空子节点的数量等于所有子节点的数量,则它隐藏父节点(甚至不使用parent()函数)。 这可能是一些代码行,但速度很快。

试一试。

最好的办法是扭转局面:

 jQuery('.main') // find the parent .hide() // hide it .find('> div:not(:empty)') // find child divs that are not empty .each(function() { // use each in order to prevent errors when set is empty jQuery(this).parent().show(); // show the parent of this non-empty element return false; // stop processing this each }) ; 

因此,这将隐藏所有.main元素,并仅显示那些具有非空子元素的元素。

见这里: http : //jsfiddle.net/L89z5o6o/

更新:

试图缩短它,这是另一种选择:

 jQuery('.main') // find the parents .not(':has(> div:not(:empty))') // select only those that have no children with content .hide() // hide them ; 

见这里: http : //jsfiddle.net/zs3ax288/

如果要检查各种子元素,可以删除div。

class=".parentClass"添加到您的父元素并添加此函数:

 var emptyCounter = 0 jQuery(".parentClass div").each(function () { if($(this).is(':empty')) { empty++ } emptyCounter-- }); if(emptyConuter === 0){ $(".parentClass").hide(); } 

http://jsfiddle.net/ktzluke10/ukb65ec8/3/

我会选择这样的简单选择器:

 jQuery(".main:empty *:empty").parent().hide();