I recently came across a straightforward to-do list. Although the inputs are properly stored in local storage, I encountered issues with the "removing item" functionality in JS. Even after removing items from the HTML, they still persist in local storage upon refreshing the page, which is puzzling to me. Additionally, I am unsure about the purpose of firstElementChild
and why it is included in the code.
/*variables */
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
// storing items retrieved from local storage in a variable
let storedItems = localStorage.getItem('tasks');
const generateTemplate = todo => {
const html = `
<li>
<span>${todo}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
}
if (!storedItems) {
storedItems = [];
} else {
storedItems = JSON.parse(storedItems);
storedItems.forEach(item => {
generateTemplate(item);
});
}
addForm.addEventListener('submit', e => {
const todo = addForm.add.value.trim();
e.preventDefault();
if (todo.length) {
generateTemplate(todo);
storedItems.push(todo);
localStorage.setItem('tasks', JSON.stringify(storedItems))
addForm.reset();
console.log(`${todo} has been added to html list`)
console.log(`Local storage now contains ${storedItems}`)
}
});
/*Removing item*/
list.addEventListener('click', e => {
console.log(e.target);
if (e.target.classList.contains('delete')) {
e.target.parentElement.remove();
let removedItem = e.target.parentElement.firstElementChild.innerText;
console.log(`${removedItem} has been removed from the html list`);
console.log(storedItems)
const newArr = storedItems.filter(item => item !== removedItem)
console.log(newArr)
storedItems = newArr
console.log(`Local storage now contains ${storedItems} `)
}
})
<!DOCTYPE html>
<html lang="en<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHr" crossorigin="anonymous">
<title>To-do List</title>
<