Argiris A Argiris A - 1 year ago 62
Javascript Question

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>

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() {
var el= $(this);
var text = el.html();
if (text.indexOf("test") !==-1){

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

Answer Source

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


or look for the closest ancestor with the class

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download