There are few ways we can do this.
Using addEventListener
The first one is simple function call targeting the element.
const el = document.getElementById("element");
el.addEventListener("click", function, false);
Read more about addEventListener on MDN
Using setAttributes
In this post, I demonstrated how we can create HTML elements with id and class. Same way we can use setAttributes to add an onclick event function.
We can also use setAttributes on the element that already exists.
Just like this:
const el = document.getElementById("element");
el.setAttribute("onclick","function");
Using onclick
This is a straightforward approach.
const el = document.getElementById("element");
el.onclick = function();
