Designer
Designer

Reputation: 895

Hide a div's span when a different div contains specific text with jquery

I have the 3 divs below:

<div class="price"><span>FREE</span> <div class="transaction-type">FOR SELL</div></div><br/>

<div class="price"><span>$250 USD</span> <div class="transaction-type">FOR SELL</div></div><br/>

<div class="price"><span>$800 USD</span> <div class="transaction-type">FOR SELL</div></div> 

What i want to do is to hide the "transaction-type" div every time the span contains the word "free".

I already know that i can use jquery like that to target and hide the specific span:

if ($('.price>span').text().indexOf('FREE') >= 0) {
$('.transaction-type').hide();
}

My problem is that my code hide also all other spans that contain different content than "FREE" word.

You can check my FIDDLE

Upvotes: 0

Views: 42

Answers (4)

A.Abdelhak
A.Abdelhak

Reputation: 140


you can check case sensitive with pattern

   $('.price > span').each(function(){
    if ($(this).text()==="FREE"){
    $(this).next().hide();
    }
    })

Upvotes: 1

smilebomb
smilebomb

Reputation: 5483

If you use contains you will still have a jQuery object at the end, with which you can simply hide it with hide():

$('.price>span:contains("FREE")').hide()

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

Can use :contains selector and siblings() or next() to target specific instances

$('.price>span:contains("FREE")').siblings('.transaction-type').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price"><span>FREE</span> <div class="transaction-type">FOR SELL</div></div><br/>

<div class="price"><span>$250 USD</span> <div class="transaction-type">FOR SELL</div></div><br/>

<div class="price"><span>$800 USD</span> <div class="transaction-type">FOR SELL</div></div>

Upvotes: 1

j08691
j08691

Reputation: 207881

You want to loop over the elements and use $(this) to refer to the one being looped over. Then use:

$('.price>span').each(function() {
  if ($(this).text().indexOf('FREE') >= 0) $(this).next('.transaction-type').hide();
})

$('.price>span').each(function() {
  if ($(this).text().indexOf('FREE') >= 0) $(this).next('.transaction-type').hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price"><span>FREE</span>
  <div class="transaction-type">FOR SELL</div>
</div>
<br/>

<div class="price"><span>$250 USD</span>
  <div class="transaction-type">FOR SELL</div>
</div>
<br/>

<div class="price"><span>$800 USD</span>
  <div class="transaction-type">FOR SELL</div>
</div>

Upvotes: 1

Related Questions