Argiris A
Argiris A

Reputation: 156

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

Upvotes: 0

Views: 79

Answers (2)

Satish
Satish

Reputation: 19

$( 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'

Upvotes: 0

epascarello
epascarello

Reputation: 207557

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();

Upvotes: 1

Related Questions