Reputation: 137
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.
Upvotes: 0
Views: 75
Reputation: 931
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
Upvotes: 1
Reputation: 1621
Hope this is what you are looking for.I have removed id in your code as the id should be unique and i have added a class cart-summary for all the spans.Once you run the below code it will append the required classes.
$('#cart .cart-summary').each(function(){
var span_value = parseInt($(this).text());
if(span_value == 0){
$(this).addClass('cart-summary__count');
}
else{
$(this).addClass('cart-summary__count_full');
}
})
.cart-summary__count{
color:green;
}
.cart-summary__count_full{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cart">
<span class="cart-summary" data-v-observable="cart-count">0</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
<span class="cart-summary" data-v-observable="cart-count">1</span>
</div>
Upvotes: 0