简体   繁体   中英

jQuery check span class and hide closest div

I am having quite a bit of trouble figuring out why this function is not working properly. I have tried using .html val trim ! :contains' '.text and other variations to test the string inside a span with a specific class but the console seems to return the object correctly however fails. Any help is appreciated.

 if (jQuery('.price').text() == '') { jQuery(this).closest(".box").hide(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> test content<br> <span class="price">$99.99</span> </div> <div class="box"> test content<br> <span class="price">$99.99</span> </div> <div class="box"> test content<br> <span class="price"></span> </div> <div class="box"> test content<br> <span class="price"></span> </div> <div class="box"> test content<br> <span class="price">$99.99</span> </div> 

The issue with your code is because you're retrieving the text() from all the .price elements at once. You instead need to loop through them and check the text individually, and then hide the related .box , like this:

 $('.price').each(function() { if ($(this).text().trim() == '') { $(this).closest('.box').hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> test content <br> <span class="price">$99.99</span> </div> <div class="box"> test content <br> <span class="price">$99.99</span> </div> <div class="box"> test content <br> <span class="price"></span> </div> <div class="box"> test content <br> <span class="price"></span> </div> <div class="box"> test content <br> <span class="price">$99.99</span> </div> 

Your need to loop true each element.

$('.price').each( function(index) {
  if ($(this).text() == "") {
    $(this).closest(".box").hide();
  }
});

But you have a problem with your HTML. Because there are 2 close neighbors with the class .box

I am not getting your exact requirement. Try below code may be will help you.

if (jQuery('.price').text() != '') {
  jQuery('.price').closest(".box").hide();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM