QSTN007
QSTN007

Reputation: 33

Hide parent div , when no child div inside

How to set display none (or add css style) on parent div, if it doesn´t contain any child div? Child div is dynamically attached by system, so we need to set a css class on parent, when is no child inside. Any jquery idea?

parent div

Upvotes: 2

Views: 4204

Answers (4)

Ankit Singh
Ankit Singh

Reputation: 24945

You don't need jQuery/ javascript/ angular or anything else

CSS3's :empty pseudo selector can help


.displayNoneWhenEmpty:empty{
  display:none;
}
<div class="displayNoneWhenEmpty">Not Empty</div>

<div class="displayNoneWhenEmpty"></div>

Inspect after running the script, and see that style applies to empty div

Upvotes: 11

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10177

I am assuming following html

HTML

<div class="parent">
  <div class="child">

  </div>
</div>

Use this jquery code

Jquery

if($('.parent').is(':empty')){
   $('.parent').hide();
}

Upvotes: 0

boomcode
boomcode

Reputation: 399

if($("<parent>").children().length == 0) 
$("<parent>").hide();

Upvotes: 0

Hyukchan Kwon
Hyukchan Kwon

Reputation: 392

Set a display: none; by default to your parent. And when you dynamically attach the child, you set display: block

Upvotes: 0

Related Questions