I need to attach an event to a dynamically created element. With jQuery I can archive this by using the following code:
$("body").on("click", ".my-element", function() {});
And if I added a new .my-element
, it automatically got the event attached.
I'm not creating the elements via document.createElement("div");
, but I'm using pjax to reload just some parts of the page, so the main JavaScript file just loads one time, for that reason events need to be attached dynamically.
How can I achieve that with vanilla JavaScript?