问题
I have a parent div containing three child divs, I want to check the child divs to see if they are empty, if they are all empty, I want to hide the parent div so the background goes away in my design.
<div class="main">
<div class="tot1"></div>
<div class="tot2"></div>
<div class="tot3">test</div>
<div>
jQuery(".tot1:empty, .tot2:empty, .tot3:empty").parent().hide();
回答1:
The other answers are good but for performance reasons I recommend this one:
$('.main').each(function () {
var $main = $(this),
$allChildren = $main.children();
$allEmptyChildren = $allChildren.filter(':empty');
$main.toggle($allChildren.length !== $allEmptyChildren.length);
});
- It works correctly even if there are multiple
.main
elements in a page. - It caches the value of
$(this)
and reuses the query results to boost performance. - It doesn't
hide()
the.main
andshow()
it again (to avoid a repaint). - It doesn't need any extra markup on the parent node.
- It works even if later you decide to change child nodes from
<div>
to something more semantic. - Not only it hides the
.main
when all children are empty, it will show them when children have text. So it handles both hiding and showing. All you have to do is to run it again.
The source code is quite explanatory: it finds all the immediate children. Then finds ones that are empty. If the number of empty children is equal to the number of all children it hides the parent node (without even using the parent()
function). This might be a few more lines of code, but it's fast.
Try it live.
回答2:
Best thing is to turn it around:
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
})
;
So this will hide all .main elements and show only those again that have non-empty children.
See here: http://jsfiddle.net/L89z5o6o/
Update:
Tried to shorten it, this is another option:
jQuery('.main') // find the parents
.not(':has(> div:not(:empty))') // select only those that have no children with content
.hide() // hide them
;
See here: http://jsfiddle.net/zs3ax288/
You can remove the div if you want to check for all sorts of child elements.
回答3:
Add class=".parentClass"
to your parent element and add this function:
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/
回答4:
I would go with simple selector like this:
jQuery(".main:empty *:empty").parent().hide();
来源:https://stackoverflow.com/questions/25213497/jquery-hide-parent-div-if-all-children-divs-html-is-empty