Home  >  Q&A  >  body text

Loop through multiple elements and calculate the price discount for each element

<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>
P粉506963842P粉506963842413 days ago480

reply all(1)I'll reply

  • P粉616383625

    P粉6163836252023-09-03 10:41:22

    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 of document.querySelector.

    document.querySelector finds the first matching element in the entire document, while priceElement.querySelector will find the first matching element in the range: priceElement.

    So the function looks more like this:

    const priceDifference = () => {
      const price = document.querySelectorAll(".price");
    
      for (i = 0; i < price.length; i++) {
        const priceElement = price[i];
    
        const regPrice = priceElement.querySelector(".old").innerText;
        const salePrice = priceElement.querySelector(".new").innerText;
        const percentage = priceElement.querySelector(".percentage");
    
        const priceNumReg = parseFloat(regPrice.substring(1));
        const priceNumSale = parseFloat(salePrice.substring(1));
    
        const finalPrice = priceNumReg - priceNumSale;
        const percent = (finalPrice / priceNumReg) * 100;
        
        if (percentage.textContent.trim() === '') {
          percentage.textContent += ' (' + percent.toFixed(0) + '% OFF)';
        }
      }
    };
    

    This code is valid , but there is still some work that needs to be done, such as missing i declarations and innerText vs. textContent, but this code can also be shortened like this:

    const parseCurrencyValue = ({ textContent }) => Number.parseFloat(textContent.replace(/^[^-+0-9.]*/u, "")),
      priceDifference = () => Array.from(document.querySelectorAll(".price"))
      .forEach((priceElement) => {
        const [
            regularPrice,
            salePrice
          ] = [ ".old", ".new" ]
            .map((selector) => parseCurrencyValue(priceElement.querySelector(selector))),
          discount = 1 - (salePrice / regularPrice),
          percentageElement = priceElement.querySelector(".percentage");
    
        if (percentageElement.textContent.trim() === "") {
          percentageElement.insertAdjacentText("beforeend", ` (${Math.round(discount * 100)} % off)`);
        }
      });
    
    priceDifference();
    .percentage {
      text-transform: uppercase;
    }
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>
    
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>
    
    <div class="price">
      <div class="old">.00</div>
      <div class="new">.00</div>
      <div class="percentage"></div>
    </div>

    reply
    0
  • Cancelreply