Hide element if it is empty

15

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

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

Problem

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. >

Question

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

    
asked by anonymous 16.01.2014 / 20:28

2 answers

15

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)

    
16.01.2014 / 20:40
0

Place the div as default

display:none

Then when filling the div with the content, place

display:block

If you use Jquery

$(elemnto).show()
$(elemnto).hide()
    
29.01.2014 / 16:08