I have the following markup:
<div class="product">
<div class="producttext">Product1</div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext">Product4</div>
</div>
I'm trying to select with jQuery the .producttext divs that are empty and then remove them.
I'm trying with this code but it's not working:
$('.producttext').each(function(){
if ($(this).is(':empty')){
$(this).remove();
}
});
Any idea what's the problem with my code?
In your code it remove only the .producttext div which is empty, the parent div .product will be there.
I think you want to remove the .product div then you can use :has() selector
$('.product:has(.producttext:empty)').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product">
<div class="producttext">Product1</div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext">Product4</div>
</div>
Or you just want to remove .producttext then use
$('.product .producttext:empty').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product">
<div class="producttext">Product1</div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext">Product4</div>
</div>
Update :
:empty - Select all elements that have no children (including text nodes). Taken from https://api.jquery.com/filter/
So whitespace in your code will treat as textNode so you need to use the below method using filter() and $.trim()(or trim())
$('.product').filter(function() {
//return $(this).text().trim() == '';
return $.trim($(this).text()) == '';
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product">
<div class="producttext">Product1</div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext"></div>
</div>
<div class="product">
<div class="producttext">Product4</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With