-1

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:

enter image description here

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
user3243499
  • 2,953
  • 6
  • 33
  • 75

1 Answers1

1
bt.onclick = function() {
    quickReplyPressed(this);
};
Kevin Pastor
  • 761
  • 3
  • 18
  • tried. Is not working. – user3243499 Apr 22 '19 at 21:07
  • 1
    Hey there! While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Wing Apr 23 '19 at 10:34