I have a dynamic button that supposed to remove his parent element from the DOM. Because its dynamic, i warpped it with DOMContentLoaded and added for each button the EventListener with 'click'. Somehow, i dont get into the callback function (deleteTodo) when click. I'll happy to know what im doing wrong. Thanks :)
document.addEventListener('DOMContentLoaded', (event) => {
let deleteBtn = document.getElementsByClassName('delete-btn');
for( let btn of deleteBtn)
btn.addEventListener('click', deleteTodo);
});
// Delete element
const deleteTodo = () => {
console.log("inside function"); // I DONT GET INTO THIS LINE WHEN CLICK
}
You can't call a function assigned to a variable that hasn't been initialised. Use a function declaration (they're automatically hoisted) rather than a function expression so you can ensure that when your code tries to add the function to the listener it's actually available. And, as you can see from the example, it doesn't matter where you add the declaration.
function addThings() {
const html = [];
for (let i = 0; i < 5; i++) {
html.push(`<div>${i} <button class="delete-btn">Delete</button></div>`)
}
return html.join('');
}
document.body.innerHTML = addThings();
const buttons = document.querySelectorAll('.delete-btn');
buttons.forEach(button => {
button.addEventListener('click', deleteTodo, false);
});
function deleteTodo() {
this.parentNode.remove();
}