-1

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

Serafim
  • 11
  • If you don't know how to loop over a selection of elements in jQuery, then go read up on that first of all. – CBroe Nov 11 '21 at 12:40
  • How are the prices getting into the page in the first place? Normally it would make more sense to do your calculations before rendering the DOM, instead of scraping data out of the page, changing the locale representation of your numbers, doing some math, and changing the locale representation of the results, and then writing back to the page. – Daniel Beck Nov 11 '21 at 20:03

1 Answers1

0

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>
David Lukas
  • 1,184
  • 2
  • 8
  • 21