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
.
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?
2
Answers
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
.Don’t use JS if a thing is achievable with CSS.
There’s
:has
css selector, check the browser compatibility though:https://developer.mozilla.org/en-US/docs/Web/CSS/:has#browser_compatibility
But you can do that more simple – use
min-height
: