bldev bldev - 2 months ago 6
CSS Question

Dynamically Change CSS with Javascript or jQuery

I have a snippet of code in which I would like to change the css dynamically based on the values being greater than 0. For a value of '0' the class = 'cart-summary__count'. For a value greater than '0' class = 'cart-summary__count_full'.

<span class="cart-summary__count" data-v-observable="cart-count">0</span>

<span class="cart-summary__count" data-v-observable="cart-count">1</span>


*edit:

<div id="cart-summary">
<span class="cart-summary__count" data-v-observable="cart-count">0</span>
<a href class="cart">example.com</a>
</div>


change to:

<a href class="cart-full">example.com</a>


I am still learning Js and any help would be greatly appreciated. The cart value can change on the page when adding an item.

Answer

Please use this Code

$(document).ready(function() {
  $("span").each(function(){
     if (parseInt($(this).text()) > 0){
       $(this).removeClass("cart-summary__count");
       $(this).addClass("cart-summary__count_full");
     }
  });
});

Refer this Fiddle

Edit

Based on your edit, use the following code.

HTML

<div id="cart-summary">
  <div class="cartContainer">
    <span class="cart-summary__count" data-v-observable="cart-count">0</span>
    <a href class="cart">example.com</a>  
  </div>
  <div class="cartContainer">
    <span class="cart-summary__count" data-v-observable="cart-count">1</span>
    <a href class="cart">example1.com</a>  
  </div>
</div>

JS

$(document).ready(function() {
  $("span").each(function(){
     if (parseInt($(this).text()) > 0){
            $(this).parent().find('a').removeClass("cart");
            $(this).parent().find('a').addClass("cart-full");
     }
  });
});

CSS

.cart-full  {
  border : 2px solid red
}

.cartContainer {
  padding-top : 5px;
}

Refer New Fiddle

Comments