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粉1436404962023-09-09 18:10:53
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.
Check if the script can be moved below the HTML tag containing class="cart-box", preferably before the
closing tag.Try to execute updatetotal() after the DOM is fully loaded:
window.addEventListener("DOMContentLoaded", () => { updatetotal() });
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.