How to properly use jQuery This?

I'm confused on how to use $(this) properly with jQuery. I have a list of prices and want to hide a sup tag if the price is "Free"

This is my HTML -

<li class="price">
  <h2><sup>$</sup><sub>Price</sub></h2>
</li>

This is my jQuery to hide 'sup'

if(
    $("h2:contains(Free)") 
){
    ('sup').css('display', 'none');
};

But I don't want to hide every price, I just want to target the ones in the list that are "Free".

I was thinking something like -

if(
    $(".price h2:contains(Free)") 
){
    $this.('sup').css('display', 'none');
};

How can I target using $(this) in this scenario?

3 answers

  • answered 2020-10-27 22:59 Barmar

    You don't need to use $(this). You can do this all with a single selector to select the <sup> inside the matching .price elements.

    $(".price:contains(Free) sup").hide();
    

  • answered 2020-10-27 22:59 charlietfl

    You could target the h2 sub:contains(Free) and use prev() to target the <sup>

    $('.price h2 sub:contains(Free)').prev('sup').hide()
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
    <li class="price">
      <h2><sup>$</sup><sub>Price</sub></h2>
    </li>
    <li class="price">
      <h2><sup>$</sup><sub>Free</sub></h2>
    </li>
    <li class="price">
      <h2><sup>$</sup><sub>Price</sub></h2>
    </li>
    
    
    
    </ul>

  • answered 2020-10-27 23:07 Patriot

    You can use the siblings and children selectors in JQuery to modify elements on the same level or below level like this:

     $("h2:contains(Free)").children().css('display', 'none');