简体   繁体   中英

Jquery check if element exists then add class to different element

I don't know much about jquery at all, so bear with my ignorance, but I'm pretty sure I can accomplish this with jquery.

I need jquery to check if an element exists, and if so, add a class to a different element. For example,

if class "minimal-price-link" exists, then add a class to "regular-price" or what I really am wanting to do is make the regular-price strikethrough.

Here's the code:

<div class="price-box">
   <span class="regular-price" id="product-price-2">
       <span class="price">$240.00</span>
   </span>               

   <a href="http://stemulation.com/order/sfs30.html" class="minimal-price-link">
       <span class="label">Your Price:</span>
       <span class="price" id="product-minimal-price-2">$110.00</span>
   </a>
</div>

this should do it...

$(function() {

  $("a.minimal-price-link").each(function(){

    // it would be easy to wrap it with strike
    $(this).closest('.price-box').find("span.regular-price").wrap("<s>");

    // or you can also add a class
    // $(this).closest('.price-box').find("span.regular-price").addClass("strike");
  })

});​

demo

if($('.minimal-price-link').length != 0)
{
  $('.regular-price').addClass('strikethrough');
}

If any element has the minimal-price-link class, add the strikethrough class to all elements with the regular-price class. This may not be exactly what you want, but it should give you the idea.

if ($("a.minimal-price-link").length > 0)
{
    $("span.regular-price").addClass("yourclass");
}

<style type="text/css">
    .yourclass { text-decoration: line-through; }
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM