jqueryjquery-selectorsparent

jQuery find next div within a parent of $this


I'm having troubles targeting a particular div within a loop of divs.

My code below is a single item that is duplicated many times on a page. If the span with the class of edd_price has the text 'Free' inside it I want to hide the div class 'vat' of just this item.

<div class="product-thumb">
  <a href="http://tb.eldo.co.uk/downloads/achieving-sales-on-the-telephone-sample-notes/">
  <div class="thum">
    <img width="185" height="150" src="blah"/>
  </div>
  <div class="title">Title goes here</div>
  <div class="price">
    <span class="edd_price">Free</span> 
  </div>
  <div class="vat clear">
    price excluding 20% vat                             
  </div>
</a>

Everything I've tried either affects nothing or all the items on the page, heres what I think should work -

$(document).ready(function() {
if ($(".edd_price").contains("Free")) {
  $(this).parent().next('div.vat').hide();
}
});

Solution

  • First of all your condition is not working, the contains method should be this way:

    if ( $(".edd_price:contains(free)"))
    

    Take a look here: http://www.w3schools.com/jquery/sel_contains.asp

    In condition you have to get the element again because your this isn't him. This is not a callback. Then:

    $(function() {
        if ( $(".edd_price:contains(free)")) {
            $('.edd_price:contains("Free")').parent().next('.vat').hide();
        }
    });
    

    Here is the demo: https://jsfiddle.net/87qcfng8/

    Ps: Your first div is not closed, so close it.