PeterPakla
PeterPakla

Reputation: 179

How can I hide div if it is empty?

How to hide a div element if it's empty?

html structure:

<div class="row">
     <div class="col-md-5">
         <div class="left-col"></div>
     </div>
     <div class="col-md-7">
        <div class="right-col"></div>
     </div>
</div>

I always know that left-col wont be empty, but right-col might be. If it's empty, I want to hide the whole row.

I tried the following - but no changes.

$(document).ready(function () {
      $('right-col:empty').hide();
});

Upvotes: 1

Views: 1778

Answers (3)

fen1x
fen1x

Reputation: 5860

If you want to hide the whole row, you should try

$('.right-col:empty').parent().parent().hide();

or

$('.right-col:empty').closest('.row').hide();

If you you want to hide only right-col, you can do it using only css:

.right-col:empty {
    display: none;
}

Upvotes: 2

4b0
4b0

Reputation: 22323

You are using class so use . .

$(document).ready(function () {
     $('.right-col:empty').hide();
});
.right-col
 {
    background-color: lightblue;
     height: 200px;
    width: 50%;
}
.left-col
 {
    background-color: red;
     height: 200px;
    width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
     <div class="col-md-5">
         <div class="left-col"></div>
     </div>
     <div class="col-md-7">
        <div class="right-col"></div>
     </div>
</div>

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

You are missing . in class selector, ie

Change it:

$('right-col:empty').hide();

to

$('.right-col:empty').hide();

Upvotes: 0

Related Questions