Categories
JavaScript Answers

How to add click event handler to dynamically added button with JavaScript?

Spread the love

Sometimes, we want to add click event handler to dynamically added button with JavaScript.

In this article, we’ll look at how to add click event handler to dynamically added button with JavaScript.

How to add click event handler to dynamically added button with JavaScript?

To add click event handler to dynamically added button with JavaScript, we can set the buttons’ onclick property to the event handler function.

For instance, we write:

const button = document.createElement('button')
button.textContent = 'click me'
button.onclick = () => {
  console.log('clicked')
}

document.body.appendChild(button)

to create the button with createElement.

Then we set its textContent to 'click me'.

Next, we set the onclick property to the click event handler.

Finally, we call document.body.appendChild with button to add the button as the child of the body element.

As a result, when we click on the button, we see 'clicked' logged.

Conclusion

To add click event handler to dynamically added button with JavaScript, we can set the buttons’ onclick property to the event handler function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *