Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide div's if they are empty

Tags:

jquery

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?

like image 723
Blankman Avatar asked Mar 16 '11 15:03

Blankman


People also ask

How do I hide a Div which has no children?

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!

How to make a Div look empty when the Div is empty?

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.

How to hide and show a <Div> in HTML?

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:

What is the empty selector used for in CSS?

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'; } });


2 Answers

jQuery has a :empty selector. So, you can simply do:

$('div.section:empty').hide();
like image 96
Rocket Hazmat Avatar answered Oct 24 '22 10:10

Rocket Hazmat


Here is a CSS3 solution for anyone who is interested

div:empty {
  display:none;
}
like image 26
Elliot Wood Avatar answered Oct 24 '22 09:10

Elliot Wood