Hide span if condition with jQuery

1.3k Views Asked by At

I want to make this span hide if value === 0

<span class="amount">0</span>

Then i make mini-cart-remove.js and added to header.

This is my code:

 (function($) {

    $(document).ready(function() {

    if ($('.amount') === 0 ) {
        $('.amount').hide();
    }

    });
})(jQuery);

But can't hide the span.

What i am doing wrong?

2

There are 2 best solutions below

5
On BEST ANSWER

You have to get the text in the span and then compare it to 0, for this you can use .text()

if ($.trim($('.amount').text()) === '0' ) {
    $('.amount').hide();
}

If you want have multiple spans you'll have to loop through them to hide them

(function($) {

    $(document).ready(function() {
      $('.amount').each(function(){
        if ($(this).text() === '0' ) {
            $(this).hide();
        }
      });
    });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="amount">0</span>
<span class="amount">1</span>
<span class="amount">2</span>
<span class="amount">3</span>
<span class="amount">4</span>

0
On

I face it before cause I set display:block in my class so, now I never set any display attribute in class just use show() or hide() to let elements display or not I face it before cause I set display:block in my class so, now I never set any display attribute in class just use show() or hide() to let elements display or not

maybe you set display:block; in your .amount class?