I am populating a <ul></ul>
with <li></li>
using fetch
method api request.
The ul looks like the code below:
<ul id="todos" class="collection">
</ul>
The script that populates the todos:
fetch("http://localhost:3000/api/todos")
.then((resp) => resp.json())
.then((data) => {
let todos = data;
return todos.map(todo => {
let liTodo = createNode("li");
liTodo.innerHTML = '<button class="btn-small remove-todo" onclick="' + deleteTodo(`${todo._id}`) + '">Delete' + '</button>';
liTodo.classList.add("collection-item");
append(ulTodos, liTodo);
});
function createNode(element) {
return document.createElement(element); // Create the type of element you pass in the parameters
}
function append(parent, el) {
return parent.appendChild(el); // Append the second parameter(element) to the first one
}
function deleteTodo(id) {
console.log("deleteTodo function called " + id);
}
Problem:
Upon loading the page and checking console
, I can see that deleteTodo()
function is invoked even though I did not click it.
Do you know how can I properly pass the deleteTodo()
with the id
only when it is clicked?
Any help is greatly appreciated. Thanks.