In my code, I have a h1 container with h1 element inside like below :
Title H1
As Jozef Cipa's answer recommended, event delegation would probably be the best approach for doing what you are trying to accomplish. Without good reason to do something else, that is the way to go.
That said, it is also possible to detect elements being added/removed from the page using Mutation Observers and dynamically add event handlers.
var container_h1 = document.getElementById("container_h1");
function remove_h1(){
container_h1.innerHTML = "";
}
function insert_h1() {
container_h1.innerHTML = '<h1 id="h1">Title H1</h1>';
}
let h1ClickHandler = function(evt) {
alert(evt.target.innerHTML);
},
addH1ClickHandler = function (nodes) {
nodes.forEach(function (node) {
node.addEventListener("click", h1ClickHandler, false);
});
},
h1Added = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList' && mutation.addedNodes.length > 0) {
addH1ClickHandler(mutation.addedNodes);
}
}
};
// add click handlers to any existing h1 tags on load
addH1ClickHandler(container_h1.querySelectorAll('h1'));
// start observing for new h1 tags being added
var observer = new MutationObserver(h1Added);
observer.observe(container_h1, {
childList: true
});
<input type="button" value="remove H1" onclick="remove_h1();">
<input type="button" value="insert H1" onclick="insert_h1();">
<div id="container_h1"><h1 id="h1">Title H1</h1></div>
Instead of h1.addEventListener(...)
add
document.body.addEventListener('click', function(element) {
if (element.target.nodeName == 'H1') {
// your code
}
})
So you bind event listener to body
rather than h1
.
The thing is that your h1.addEventListener(...)
is only applied on currently in DOM existing <h1>
elements, but not on dynamically created ones.
http://www.theappguruz.com/blog/dynamic-event-binding-demo-jquery
In jQuery, how to attach events to dynamic html elements?