How can i remove a localStorage value from a string, without hardcoding the value?

Tags: ,



I’m messing around with JS and localStorage, creating a todo-list. When an item in the list is clicked, it changes its CSS class, and it should be deleted from localStorage. The value of the item is decided by the user, so i cant hardcode in

localStorage.removeItem('Do the dishes');

for example.

I have tried doing this:

localStorage.removeItem(ev.target.innerText);

(longer version below). It doesn’t give me an error, but it also doesn’t remove the item from localStorage.

var taskList = document.querySelector('ul');

taskList.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');

    let tasks;
    if(localStorage.getItem('tasks') === null ){

        tasks = [];

    }
    else {
        tasks = JSON.parse(localStorage.getItem('tasks'));  
        console.log("TaskList Is Not empty"); 

        tasks.forEach(function(task, index){
            if(ev.target.innerText === task){
                localStorage.removeItem(ev.target.innerText);
                console.log("Removed"); 
            } 
            else{
                console.log("Else Executed");
            }
        }

The tasks are all added to a localStorage key called “Tasks”:

function storeTaskInLocalStorage(newTask){
let tasks;
if(localStorage.getItem('tasks') === null ){
    tasks = [];
}else{
    tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.push(newTask);
localStorage.setItem('tasks', JSON.stringify(tasks));
}

As stated, the item should be gone from localStorage, but it isn’t. It’s probably a fault in my code, but i can’t seem to find any other way of doing it on the internet, so any help would be much appreciated!

If the full project is needed to troubleshoot or anything, just let me know and i can upload it to codePen or something 🙂

Answer

That should do the job:

var taskList = document.querySelector('ul');

taskList.addEventListener('click', function (ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');

    let tasks;
    if (localStorage.getItem('tasks') === null) {

      tasks = [];

    } else {
      tasks = JSON.parse(localStorage.getItem('tasks'));
      console.log('TaskList Is Not empty');

      const taskId = tasks.indexOf(ev.target.innerText);

      if (taskId !== -1) {
        tasks.splice(taskId, 1);

        localStorage.setItem('tasks', JSON.stringify(tasks));
      }
    }
  }
});

I hope that tasks is an array of strings where you store your todos – if not please tell me so I’ll adapt code.



Source: stackoverflow