I´m building a simple todo list and will use the splice method to remove items from the list. I can't get it to work. I get the spliced item to the console so the "connection" between my remove button and my remove function seems to work. I also tried the slice method and that works, but for some reason the splice method won't work. Below is the array that I use to push in my new items to my class, the function that creates the HTML for the new todo items and the remove items function. Any idea why the splice method won't work?
//ARRAY FOR NEW TODO ITEMS
let newTodo: Todo[] = [];
// FUNCTION THAT CREATES THE HTML FOR THE NEW TODO ITEM
let doneBtn = document.createElement("button");
function htmltask() {
let taskDiv = document.createElement("div");
taskDiv.innerHTML = "";
for (let i = 0; i < newTodo.length; i++) {
taskDiv.className = "taskDiv";
taskDiv.innerHTML = newTodo[i].todoItem;
let btnContainer = document.createElement("div");
btnContainer.className = "btnContainer";
// REMOVEBTN //
let removeBtn = document.createElement("button");
removeBtn.innerHTML = "REMOVE";
removeBtn.addEventListener("click", (e) => {
remove(e, i);
});
// DONEBTN //
let doneBtn = document.createElement("button");
doneBtn.innerHTML = "DONE";
doneBtn.className = "doneBtn";
newTaskDiv.appendChild(taskDiv);
taskDiv.appendChild(btnContainer);
btnContainer.appendChild(doneBtn);
btnContainer.appendChild(removeBtn);
}
localStorage.setItem("newTodo", JSON.stringify(newTodo));
}
// FUNCTION TO REMOVE ITEMS
function remove(e: Event, i: number) {
newTodo.splice(i, 1);
htmltask();
}
Changed your code a bit, now it works:
<div>
<button onClick="htmltask()">Action!</button>
<div id="tasks" />
</div>
type Todo = { todoItem: string }
let newTodo: Todo[] = [
{ todoItem: 'Eat'},
{ todoItem: 'Sleep'},
{ todoItem: 'Code'},
];
function htmltask() {
const allTasksDiv = document.getElementById("tasks");
allTasksDiv.innerHTML = "";
for (let i = 0; i < newTodo.length; i++) {
const taskDiv = document.createElement("div");
taskDiv.className = "taskDiv";
taskDiv.innerText = newTodo[i].todoItem;
const btnContainer = document.createElement("div");
btnContainer.className = "btnContainer";
// REMOVEBTN //
const removeBtn = document.createElement("button");
removeBtn.innerText = "REMOVE";
removeBtn.addEventListener("click", (e) => remove(e, i));
// DONEBTN //
let doneBtn = document.createElement("button");
doneBtn.innerText = "DONE";
doneBtn.className = "doneBtn";
btnContainer.appendChild(doneBtn);
btnContainer.appendChild(removeBtn);
taskDiv.appendChild(btnContainer);
allTasksDiv.appendChild(taskDiv);
}
localStorage.setItem("newTodo", JSON.stringify(newTodo));
}
function remove(e: Event, i: number) {
newTodo.splice(i, 1);
htmltask();
}
Though I would recommend remove item in another way: search for the item's div and remove it. Instead of recreating the whole todos block from scratch.