1 Whe" /> 1 Whe" /> 1 Whe"/>

How can I add a class to a parent element if the child element's value is greater than zero?

42 Views Asked by At

I've got a shopping cart that produces the following code:

<a href="/cart/" class="et-cart-info">
  <span>1</span><!-- cart contents number -->
</a>

When a user has an item, I would like the class .yipi added to .et-cart-info. When it's empty and shows <span>0</span> I want the class removed.

I've tried the following code but no avail:

jQuery(function($){
    var amount = $(".et-cart-info span").val();
  if( amount >= '1' ) {
      $(".et-cart-info").addClass('yipi');
  }
});

Thanks!

2

There are 2 best solutions below

0
Stuart On BEST ANSWER

You need to get the text content of the span, not val().

jQuery(function($){
  var amount = $(".et-cart-info span").text();
  if( amount >= '1' ) {
    $(".et-cart-info").addClass('yipi');
  }
});
0
J.C On

Try This

jQuery(function($){
        var amount = $(".et-cart-info span").html();
      if( Number(amount) >= 1 ) {
          $("a.et-cart-info").addClass('yipi');
      }
    });