You can use the :empty
pseudo-selector in your CSS to handle childless elements (text or sub-elements)
#page-alerts {
margin:25px 0;
}
#page-alerts:empty {
margin: 0;
}
Example in jsFiddle. This switch works in all browsers except IE8 or earlier. In the above example I assign margin
to 0
, but you could use display: none
if you want to hide the element at all.
Note: This rule worked well on your fiddle because you used CSS to assign the style; if you assign the inline style (as in your question code) then I think it will take precedence over CSS rules. In that case, only using JavaScript to resolve. Example :
$("#page-alerts")
.toggle(!$("#page-alerts").is(":empty"))
.bind("propertychange DOMSubtreeModified", function() {
$(this).toggle(!$(this).is(":empty"));
});
(Source of code to hear for changes to div
: this answer in SOEN; there is no mention of which browsers support the DOMSubtreeModified
event, but that other response says that it can be replaced with propertychange
in IE)