I have some divs that maybe be empty (depending on server-side logic).
<div id="bar">
<div class="section" style="display:block;"></div>
<div class="section" style="display:block;"></div>
<div class="section" style="display:block;"></div>
</div>
If they don't have any html inside the div's (with class section), I just want to hide them.
How can I do this?
A much cleaner approach is to just use CSS. The above style will hide divs which are emtpy. The :empty selector matches every element that has no children (including text nodes). Avoid using JS if CSS does the trick!
You want the div to look empty when the div is empty?? The idea would be to hide the empty div and its associated label. So, say the Phone value is empty it should look like this: <div class="row"> <div class="col"><strong>Address</strong>:</div> <div class="col-3">Beverly Hills 90210</div> </div> A much cleaner approach is to just use CSS.
Hiding and showing a <div> in HTML is quite an easy thing. You can do it with CSS or a small piece of JavaScript and jQuery codes. The document.getElementById will select the <div> with given id. You should set the display to "none" so as to make it disappear when clicked on <div>: Another example of hiding and showing div with JavaScript:
The :empty selector matches every element that has no children (including text nodes). Avoid using JS if CSS does the trick! var divs = document.querySelectorAll ('.row > div'); divs.forEach (function (element) { var text = element.textContent; if (text === '') { element.style.display = 'none'; } });
jQuery has a :empty
selector. So, you can simply do:
$('div.section:empty').hide();
Here is a CSS3 solution for anyone who is interested
div:empty {
display:none;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With