AddEventListener "Click" Is Not Responding in Ejs File

header.ejs

footer.ejs

delicacies.ejs

cart.js

I am trying to make the element("span.cartcount") display as it is set to display: none in the CSS file. It should be displayed when I click on addtocart button (a.addtocartbutton).

I will also be glad if I can get directions or an alternative way of going about shopping cart system with express.js

Thank you.

1

1 Answer

document.querySelector() returns just the first element matching the selector. You have a foreach() loop that creates multiple items, you need to add the event listener to all of them. So you need to use document.querySelectorAll() and loop over them.

let addToCartButtons = document.querySelectorAll("a.addtocartbutton");
let cartCount = document.querySelector("span.cartcount");

addToCartButtons.forEach(btn => btn.addEventListener("click", (event) => {
    event.preventDefault();
    cartCount.style.display = "inline";
}));
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest