How to add onclick event programmatically with JavaScript?

Sometimes, we want to add onclick event programmatically with JavaScript.

In this article, we’ll look at how to add onclick event programmatically with JavaScript.

How to add onclick event programmatically with JavaScript?

To add onclick event programmatically with JavaScript, we can set the onclick property of an element.

For instance, we write:

<button>
  click me
</button>

to add a button.

Then we write:

const button = document.querySelector('button')
button.onclick = () => {
  console.log('clicked')
}

to select the button with querySelector.

Then we set the button.onclick property to a function that logs 'clicked'.

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

Conclusion

To add onclick event programmatically with JavaScript, we can set the onclick property of an element.