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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}); |