I created a function that when a button is clicked an element is duplicated. If you then click on that element, a function is executed that deletes that element. The problem is that the delete function only works on the first button (which is present on the page since js is loaded), while it does not work on buttons that are added later (which are not present while js is loaded). Is there any way that would make the delete function run on the new buttons as well?
This is the add function
add() {
let clone = document.querySelector('#element').cloneNode(true);
document.querySelector('#element2').append( clone );
}
and this is the remove function (e is the clicked element)
remove(e) {
e.parentNode.remove();
}
CodePudding user response:
You have to attach the event listener on the new buttons each time you add one
add() {
let clone = document.querySelector('#element').cloneNode(true);
clone.addEventListener("click", remove); // assuming the clicked and remove is that clone and not the #element2
document.querySelector('#element2').append( clone );
}