Loop through multiple elements and calculate the price discount for each element
P粉506963842
2023-09-02 17:14:31
<p>I'm trying to find the percentage difference between the old price and the new price for each individual <code><div></code>. Currently, my code only gets the percentage difference of the first <code><div></code> and loops the same percentage difference to the remaining <code><div></code> ;middle. Does anyone know how to update this code to target each individual <code><div></code> instead of just looping through the first one? I want to implement this functionality using pure JavaScript, no jQuery required. </p>
<p>
<pre class="brush:js;toolbar:false;">const priceDifference = () => {
const regPrice = document.querySelector('.old').innerText;
const salePrice = document.querySelector('.new').innerText;
const priceNumReg = parseFloat(regPrice.substring(1));
const priceNumSale = parseFloat(salePrice.substring(1));
const finalPrice = priceNumReg - priceNumSale;
const percentage = document.querySelectorAll('.percentage');
const percent = (finalPrice / priceNumReg) * 100;
for (i = 0; i < percentage.length; i ) {
if (percentage[i].textContent.trim() === '') {
percentage[i].textContent = ' (' percent.toFixed(0) '% OFF)';
}
}
};
priceDifference();</pre>
<pre class="brush:html;toolbar:false;"><div class="price">
<div class="old">$14.00</div>
<div class="new">$6.00</div>
<div class="percentage"></div>
</div>
<div class="price">
<div class="old">$12.00</div>
<div class="new">$5.00</div>
<div class="percentage"></div>
</div>
<div class="price">
<div class="old">$18.00</div>
<div class="new">$3.00</div>
<div class="percentage"></div>
</div></pre>
</p>
You have to loop over each
.price
element, not each.percentage
, because each individual calculation you are trying to perform is based on a separate<div class="price">
range.Do all calculations inside the loop, such as the current
priceElement
(which is one of your<div class="price">
elements).Now you can use
priceElement.querySelector
instead ofdocument.querySelector
.document.querySelector
finds the first matching element in the entire document, whilepriceElement.querySelector
will find the first matching element in the range:priceElement
.So the function looks more like this:
This code is valid , but there is still some work that needs to be done, such as missing
i
declarations andinnerText
vs.textContent
, but this code can also be shortened like this: