I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list'); var resetNotify = document.getElementById('reset-message'); var recordCounter = document.getElementById('record-counter'); var st = window.localStorage; var count = st.clickcount; var nameArray = []; var newArr; // Set the counter on refresh if (JSON.parse(st.getItem('names'))) { recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length); theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, ''); } else { recordCounter.innerHTML = (count = 0); } function addNameRecord() { resetNotify.innerHTML = ''; var name = document.getElementById('names-field'); nameArray = JSON.parse(st.getItem('names')); count = Number(count) + 1; newArr = makeArr(nameArray); // Check if there is anything in the name array. if (nameArray != null) { nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>'); } else { nameArray = []; nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>'); } st.setItem("names", JSON.stringify(nameArray)); name.value = ''; if (!newArr[0]) { count = 1; theLIst.innerHTML = nameArray; recordCounter.innerHTML = count; } else { theLIst.innerHTML = newArr[0].join(''); recordCounter.innerHTML = count; } } // Take our string from local storage and turn it into an array we can use function makeArr() { return Array.from(arguments); } // Purge all entries, reset counter function clearArray() { st.clear(); nameArray = []; theLIst.innerHTML = ''; recordCounter.innerHTML = (count = 0); resetNotify.innerHTML = 'Array has been purged.'; } Heres the code I tried
// Delete a specific entry function clearThisItem(item) { console.log(item); localStorage.removeItem(item); console.log(localStorage.removeItem(item)) return item; }
localStorage.removeItem()?.removeItem()is the correct way, so you must be using it incorrectly.