Skip to content
Advertisement

Multiple buttons with the same class name but only the first one works

I’m fairly new to JS and I currently working on the front-end of a very basic ecommerce page as a personal project.

Here’s my question, all the “items” on the page are exact the same aside from their name. When I click on “buy”, I’d like to send the name of the respective item to the cart. However every time I click on any buy button, instead of sending the title of the item I just clicked, it always sends the “Item 1”.

I’ve been trying to figure this out for sometime now but no luck so far.

Thanks in advance!

–HTML–

JavaScript

–JS–

JavaScript

Advertisement

Answer

This is because querySelector returns the first instance of the element in the DOM that corresponds to the class you are looking for. To fix this, first of all, I listened to the event of clicking all the buttons with querySelectorAll, and in the function itself, I searched for .product-name according to the parent closest to the button that has the class product

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement