Why am I getting Cannot read property of undefined (read 'innerHTML')?
P粉205475538
P粉205475538 2023-09-08 21:26:37
0
1
744

I'm creating a shopping cart for an e-commerce site and I'm updating the total price of the item in relation to quantity, but I'm 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 almost everything I think I might be making a small mistake somewhere?

P粉205475538
P粉205475538

reply all(1)
P粉143640496

Either the element class name is written wrong (unlikely since you've checked it 100 times haha), or you're trying to access it before rendering.

  1. Check if the script can be moved below the HTML tag containing class="cart-box", preferably before the

    closing tag.
  2. Try to execute updatetotal() after the DOM is fully loaded:

    window.addEventListener("DOMContentLoaded", () => {
       updatetotal()
     });
  3. If you are rendering an element via Ajax after the DOM is fully loaded, you can try this trick: write a function that checks if the element exists, and if not, wait a few seconds and call the function recursively again:

    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, but it gets the job done.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!