I have an array called 'filteredTasks', for each task I want to create a button in a Div and add an onclick function to that button. I created some code (which you can see below, first block) to do that. Which didnt work, the buttons get created properly but the onclick function only gets added to the last button. When I use the exact same code, but splitted up into 2 different forEach callbacks (which you can also view below, second part), it does work. In short, when trying to create the buttons and adding a onclick function to each when created, only the last button properly receives an onclick function. But when I create all the buttons first, then add an onclick function to each, it does work. I fail to figure out why this is. Any better developer here that can point out to me why? Thanks alot!
filteredTasks.forEach(function(task) {
var buttonId = task.taskName.replace(/\s/g, '') + 'Button'
var taskHTML = `<button class="taskButton" id="${buttonId}">${task.taskName}</button>`;
taskDiv.innerHTML += taskHTML;
var button = document.querySelector(`#${buttonId}`);
button.onclick = function() {performTask(task)};
});
};
filteredTasks.forEach(function(task) {
var buttonId = task.taskName.replace(/\s/g, '') + 'Button'
var taskHTML = `<button class="taskButton" id="${buttonId}">${task.taskName}</button>`;
taskDiv.innerHTML += taskHTML;
});
filteredTasks.forEach(function(task) {
var buttonId = task.taskName.replace(/\s/g, '') + 'Button'
var button = document.querySelector(`#${buttonId}`);
button.onclick = function() {performTask(task)};
});
};