Native JavaScript: Event Handling of Dynamic HTML Elements

In jQuery, if you dynamically add an element to the DOM and want to attach an event handler to it, that’s very easy with the following line of code.

$("body").append("<div class='a'></div>");
$(document).on("click", "div.a", function (event) {
// do something when the div is clicked
});

However, if you try to do that with native Javascript, you have to do with by checking for all clicks on the page and only acting on clicks where the click occurred on the element you want to act on.

document.querySelector('div.a').addEventListener('click', function(event) {
if (event.target.className === 'a') {
// do something
}
});

Obviously that’s no good. One workaround is to put the HTML element in the page somewhere(if that’s possible in your case), then detach and attach it to where you want to dynamically put it, then add an event listener specifically for that element, e.g.

// get the div
var div = document.querySelector('div.a');
// detach the div
div = div.parentNode.removeChild(div);
// attach the div somewhere else
var footer = document.querySelector('.footer');
footer.insertAdjacentHTML('afterend', div.outerHTML);
// listen to an event on the element and handle it
div.addEventListener("click", function (event) {
// do something
});