简体   繁体   中英

Hide specific elements if another element contains a string with jQuery

I have a carousel of coupons at my site and I want to achieve the following functionality:
For each coupon, if the brandName contains the text 'test' then hide the div that contains it which means that I want to hide all the coupons that have 'test' at their brandName.
So, suppose that the each coupons div is the following:

<div class="coupon-box">
  <div class="brandName">Test1</div>
  <div class="coupon-image"><img src="coupon-image.jpg"></div>
</div>

I want to hide every coupon that has 'test' at his title. I have actually managed to do the first part(getting the brandNames that have the text) but I don't know how to hide its coupon box.
What I've done until now is the following:

$( document ).ready(function() {
    $('.brandName').each(function(){
       var el= $(this);
       var text = el.html();
       if (text.indexOf("test") !==-1){
          //missing-code
       }
   });
});

Any suggestions? I tried adding $('.coupon-box').css('display', 'none'); but it just hides all coupons

It does not work because you are selecting all the elements and not the one you are currently in. So you need to look for the parent element of the item.

So select the parent of the element

el.parent().hide();

or look for the closest ancestor with the class

el.closest(".coupon-box").hide();
$( document ).ready(function() {
    $('.brandName').each(function(){
       var el= $(this);
       var text = el.html();
       if (text.indexOf("test") !==-1){
         el.parent().css('display', 'none');
       }
   });
});

Be careful, because 'test' != 'Test'

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