I am trying to create a list of buttons and to add the onClick
event listener as follows:
var buttonLabel = "Proceed";
// create button element
var bt = document.createElement('button');
// add class name to created button
bt.className = "btn btn-primary shadow-none quickRepliesButton";
// add type to created button
bt.type = "button";
// add value to created button. Value is our button label in our case
bt.value = buttonLabel;
// add onclick event listener
bt.onclick = "quickReplyPressed(this)";
// create text and add to button
document.createTextNode(buttonLabel);
bt.appendChild(document.createTextNode(buttonLabel));
Following is the DOM snippet of the created button:
With the above code, I am able to create a button and show it to the UI. But the created button does not have any onclick
attribute.
How to properly add the onclick event listener to the created button?
I have just started learning front end dev and based on my studies and research online, I am not sure how to achieve my goal.
Update
Regarding the proposed duplicate, I have found that the marked answer does not work. Probably, because the other question is about a different problem context but has almost the same intention. In the other question, the question author tried to add onclick event listeners to an already existing DOM whereas I am searching for the correct way to add and eventlistender to a dynamically created DOM element, button.
Update 2
I solved the problem by referring to this link - Add onclick event to newly added element in JavaScript. I would say this link is the correct "already answered" link not the one which is currently marked.