Although inserting a number into a string of HTML with an inline event handler will work, you shouldn’t do it. It’s fragile and can easily lead to script injection vulnerabilities (XSS), and prevents you from using a Content-Security-Policy that would effectively limit the same risks elsewhere.
You’re already halfway to doing the right thing by using the DOM to create the list item. Follow through and avoid embedding JavaScript in HTML in JavaScript:
fillTask();
function fillTask() {
tasksList.textContent = '';
let index = 0;
for (let task of tasks) {
let thisIndex = index;
index++;
let deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.onclick = () => {
mytask(thisIndex);
};
let li = document.createElement('li');
li.append(' ', deleteButton);
tasksList.append(li);
}
}
Note: writing it this way does need a separate variable thisIndex
scoped to the loop iteration. Separating out creating a list item into a new function might be cleaner in this and other respects:
fillTask();
function createTaskItem(index) {
let deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.onclick = () => {
mytask(index);
};
let li = document.createElement('li');
li.append(' ', deleteButton);
return li;
}
function fillTask() {
tasksList.textContent = '';
let index = 0;
for (let task of tasks) {
tasksList.append(createTaskItem(index));
index++;
}
}