Question:
I wrote up a code that displays food items on the screen by creating elements of varied tags dynamically. And I’ve placed the entire process in one function called displayMenuItems. Now the first set of dynamically created buttons (i.e ‘add-btn’ buttons), when I add an event to them, the event will fire without a hitch when clicked. However the second set of dynamically created buttons (i.e ‘delete-btn’ buttons), when an event is added to them, the event will not fire when clicked. I’ve no idea why this complication arises when the code of the second set of buttons is similar to the first set of buttons. Could you fix this problem, I would really appreciate it?Answer:
delete-btns
elements are not generated initially, but your events are only added for the first time, so that’s why all your delete events are not applied when you add them into DOM.I’d suggest that you should add an event directly on the newly added delete button every time.
If you have better answer, please add a comment about this, thank you!