Hide element if it is empty


I have a div that is used to display alerts to the user:

<div id="page-alerts" style="margin:25px 0;"></div>


Example in JSFiddle

For formatting issues, it contains margins at the top and bottom, causing a blank equal to the value of the margins, when it is empty, which breaks the layout. >


How to hide div when it is empty (without alerts ...)?

asked by anonymous 16.01.2014 / 20:28

2 answers


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 :

    .bind("propertychange DOMSubtreeModified", function() {

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

16.01.2014 / 20:40

Place the div as default


Then when filling the div with the content, place


If you use Jquery

29.01.2014 / 16:08