I have this structure:
<div class="gs-item-price">
<span class="gs-old-price">5,00</span><br>
<span class="gs-new-price">1,00</span><br>
</div>
<br>
<span class="value1"></span> %
<br>
<br>
<div class="gs-item-price">
<span class="gs-old-price">10,00</span><br>
<span class="gs-new-price">5,00</span><br>
</div>
<br>
<span class="value1"></span> %
I need to calculate and visualize the discount percentage.
I have written the following code:
var OldPrice=$('.gs-old-price').html().replace(/,/g,'.');
var NewPrice=$('.gs-new-price').html().replace(/,/g,'.');
var oldPriceNum= parseFloat(OldPrice);
var newPriceNum= parseFloat(NewPrice);
var percent= oldPriceNum - newPriceNum;
var percent1= percent/oldPriceNum;
var percent2=percent1*100;
var finalPercent=parseFloat(percent2).toFixed(0);
document.querySelector('.value1').innerHTML = finalPercent;
That visualize only the first value of the percentage.
How can I go through all the divs and get the right percentage? All help will be good
I moved both <span class="value1"></span> % to the appropriate <div class="gs-item-price"> and then I called each. I also changed placing finalPercent. See the snippet:
$('.gs-item-price').each(function() {
var OldPrice=$(this).find('.gs-old-price').html().replace(/,/g,'.');
var NewPrice=$(this).find('.gs-new-price').html().replace(/,/g,'.');
var oldPriceNum= parseFloat(OldPrice);
var newPriceNum= parseFloat(NewPrice);
var percent= oldPriceNum - newPriceNum;
var percent1= percent/oldPriceNum;
var percent2=percent1*100;
var finalPercent=parseFloat(percent2).toFixed(0);
$(this).find('.value1').html(finalPercent)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gs-item-price">
<span class="gs-old-price">5,00</span><br>
<span class="gs-new-price">1,00</span><br>
<br>
<span class="value1"></span> %
<br>
</div>
<br>
<div class="gs-item-price">
<span class="gs-old-price">10,00</span><br>
<span class="gs-new-price">5,00</span><br>
<br>
<span class="value1"></span> %
</div>