Reputation:
I am trying to add a class to the closest element if a child with class of .present has any html content.
My code at the moment....
<article>
<div class="box">
<h2>1 dec</h2>
</div>
<div class="present">
<h1>HAS CONTENT</h1>
</div>
</article>
<script>
$(document).ready(function(){
if ($(".present").html().length > 0) {
$(this).parent().addClass('active');
}
});
</script>
I have tested if condition with a console.log so is being returned as true but active class is not being added to parent element. Can anybody let me know what I am doing wrong here?
Upvotes: 1
Views: 224
Reputation: 148140
You can use filter() to get element that does not have html and then get their parent to add class
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).parent().addClass('active');
Edit
To add class to .present
you can skip .parent()
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).addClass('active');
Upvotes: 1