Sérgio Miranda Sérgio Miranda - 4 months ago 11
jQuery Question

Check each div and do action if condition is matched

I want to add some text inside a div if that div matches condition. Right now all the div's are filled up with the added text. Please check my code to better understand what I mean.
What's the best solution to achieve my goal? Thank you.



$('.col-md-3').each(function () {
if ($('.status:contains("Rent")').length > 0) {
$('.price').append('/month');
};
return false;
});

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="row">
<div class="col-md-3"><div class="status">Rent</div><div class="price">€100</div>
</div>
<div class="col-md-3"><div class="status">Rent</div><div class="price">€100</div>
</div>
<div class="col-md-3"><div class="status">For sale</div><div class="price">€1000</div>
</div>
<div class="col-md-3"><div class="status">For sale</div><div class="price">€1000</div>
</div>




Answer

Right now you're telling jQuery to check every element in the document which has the class .status. You can pass a context which should be used to only look for elements matching the selector in this exact <context>.


jQuery( selector [, context ] )

selector
Type: Selector
A string containing a selector expression

context
Type: Element or jQuery
A DOM Element, Document, or jQuery to use as context


In your example you have to use this as context as this is the current .col-md-3

$(function() {
  $('.col-md-3').each(function() {
    if ($('.status:contains("Rent")', this).length > 0) {
      $('.price', this).append('/month');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-3"><div class="status">Rent</div><div class="price">€100</div> 
  </div>
  <div class="col-md-3"><div class="status">Rent</div><div class="price">€100</div>
  </div>
  <div class="col-md-3"><div class="status">For sale</div><div class="price">€1000</div>
  </div>
  <div class="col-md-3"><div class="status">For sale</div></div><div class="price">€1000</div>
</div>