I am trying to call a function called mytask and pass index variable as a parameter. However, it seems that the compiler doesn’t recognize index.
Here is my code:
fillTask();
function fillTask() {
tasksList.innerHTML = '';
let index = 0;
for (task of tasks) {
let li = document.createElement('li');
li.innerHTML = ' <button onclick="mytask(${index})" class="delete">Delete</button> ';
tasksList.appendChild(li);
//index++;
}
}
//Delete task
function mytask(index) {
alert("Task has been deleted");
}
When I click on the delete button I am getting this error in my console:
Uncaught SyntaxError: missing ) after argument list (at index.html:1:8)
3
Answers
Replacing single quotes with backticks solved my problem like follows:
simply use backticks “ instead of single quotes ”. Otherwise string interpolation is not recognised by the interpretor.
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:
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: