Skip to content
Advertisement

AddEventListener Not Working on Dynamic DOM

I have the following function which dynamically creates a Bootstrap card:

JavaScript

Where I am declaring the button, I am attempting to use the addEventListener to generate the click event for the button. The addToCart function is defined as:

JavaScript

And for what it is worth, this is how I am making my AJAX call to get the data:

JavaScript

The issue is that the click event is never being invoked when I actually click on the button. I tried adding a debugger, setting up a breakpoint, and calling a console.log('click'); in the function, but the code never reaches any of those attempts when I click on the button.

I have also tried using onclick instead of click but with no success.

At this point, I’m not sure what I’m doing wrong.

Advertisement

Answer

I discovered the answer to my own question.

The solution was to use the appendChild method when adding my card to the parent. Documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

This was the change (in the last code block of my thread):

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