skip to Main Content

I’m creating a cart for a ecommmerce site I’m in the price of updating the total price of the items correlating to the Quantity but im running an error?

function updatetotal () {
    const cartContent = document.getElementsByClassName("cart-content")[0];
    const cartBoxes = cartContent.getElementsByClassName("cart-box");
    let total = 0;
    for (let i = 0; i < cartBoxes.length;i++) {
        const cartBox = cartBoxes[i];
        const priceElement = cartBox.getElementsByClassName("cart-price")[0];
        const quantityElement = cartBox.getElementsByClassName("cart-quanity");
        let price = parseFloat(priceElement.innerHTML.replace('$',''))
        const quantity = quantityElement.value;
        total+= price * quantity;
        document.getElementsByClassName("total-price")[0].innerText = '$' + total; 

    }
}

I’ve tried just about everything I think its a minor mistake made somewhere maybe?

2

Answers


  1. Your html code? If your Javascript code wrote before html, at that time, the element that you search is not "exist" (Javascript cannot read the html code after it). You should move Javascript to the end of <body>

    Login or Signup to reply.
  2. Either the elements classname are miswritten, (which is very unlikely, since you’ve checked it 100 times haha) or you are trying to access it before it was rendered.

    1. Check if you can move the script to execute below the HTML tag that contains class="cart-box", preferably right before the < body > closing tag.

    2. Try to execute updatetotal() after DOM is completely loaded:

       window.addEventListener("DOMContentLoaded", () => {
         updatetotal()
       });
      
    3. In cases where the rendering of elements via Ajax occurs after the DOM is completely loaded, you can try the following trick: write a function that checks if the element is present, if not you wait a few seconds and call the function again recursively:

       let cartBoxes //Global
      
       const delay = ms => new Promise(res => (setTimeout(res, ms)));
      
       async function waitForCartBoxes() {
           cartBoxes = cartContent.getElementsByClassName("cart-box");
           if (cartBoxes.length == 0) { //Not found - wait 500ms and try again.
               await delay(500);
               waitForCartBoxes();
               return
           }
       }
      

    The last solution is definitely not the best one, but gets the job done.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search