What is the native implementation for event delegation on dynamically created dom elements?
I tried looking at the jQuery source but I can\'t follow the .on
For example, we have such an html structure.
-
item 1
-
item 3
-
item 3
Note that there is an i tag inside the button.
If you want to capture exactly the right item for the Click event, you need a function like the one below.
function delegateClick(selector, callback){
let selectorItems = document.querySelectorAll(selector);
document.addEventListener('click', function(e){
let clickedItems = e.path;
for(let clickedItem of clickedItems){
for(let selectorItem of selectorItems){
if(clickedItem === selectorItem){
callback(clickedItem);
}
}
}
});
}
This offers a very similar use to jquery.
delegateClick('.btn-edit', (elm) => {
//access the clicked DOM element
elm;
});