JQuery Hide parent div if child div is empty

I looked around and found a lot of questions about this, but none of the solutions work for me. I have a structure like this:

<div class="pricetag"> <div class="price">400</div> </div> <div class="pricetag"> <div class="price"></div> </div> <div class="pricetag"> <div class="price">250</div> </div> 

What I want to do is hide the .pricetag where .price contains nothing. It can be many different .pricetag on one page, but I just want to hide them with empty .price.

Is this possible with jQuery? I tried many different scripts but no one worked properly.

+6
source share
6 answers

You can use the selector :empty , and parent , assuming that the empty .price elements .price never contain text nodes (for example, a new line character):

 $(".price:empty").parent().hide(); 

Here is a working example .

+17
source
 $('.price').each(function(){ if ($(this).text().length == 0) { $(this).parent().hide() } }) 
+1
source

working demo http://jsfiddle.net/mm4pX/1/

You can use .is(':empty') to check if the div is empty and then hide the parent div.

Hope this helps,

the code

 $('.price').each(function() { if $('.price').is(':empty') $(this).parent().hide() });​ 
+1
source

This jquery code will do it

 $(function(){ $(".price").each(function(){ if($(this).html()=="") $(this).parent(".pricetag").hide(); }); }); 

Jsbin example: http://jsbin.com/ovagus

0
source

try this jQuery script

 $(document).ready(function(e) { $('div.pricetag').each(function(key, value) { if(!$('div.price', value).html()) $(value).hide(); }); }); 
0
source

The :empty selector does not select an element if it contains spaces. If this is a problem, you can trim the item from spaces:

 function isEmpty(element){ return !$.trim(element.html()) } $(".box").each(function() { var box = $(this); var body = box.find(".box-body"); if(isEmpty(body)) { console.log("EMPTY"); box.hide(); } }); 

http://codepen.io/DanAndreasson/pen/jWpLgM

0
source

Source: https://habr.com/ru/post/919482/


All Articles