Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add style to a parent div only if it's child div content is empty?

How can I add CSS style using Jquery, to a parent div only if the parent’s child div content is empty?

Example:

 <div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>
<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent">some text</div>
    </div>
</div>
<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>

So if there is no text inside a subContent class, then I want to add padding-bottom: 20px to parentDivClass. If there is text inside subContent, then no CSS to be added on parentDivClass.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I approached it like this but for some reason it is not adding style to parentDivClass if subContent has no text:

if( $('.subContent').is(':empty') )
{
    $('.parentDivClass').css({'padding-bottom': '20px'});
}

Is my logic going wrong some where?

>Solution :

Your if condition is true if any .subContent div is empty. And the .css() call doesn’t only apply to the parent of the empty div, it’s done on all .parentDivClass elements.

You need to relate the empty .subContent div to its containing .parentDivClass.

$(".subContent:empty").closest(".parentDivClass").css({'padding-bottom': '20px'});
.parentDivClass {
  background-color: yellow;
  border: solid black 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>

<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent">not empty</div>
    </div>
</div>

<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading