So I have an array in my localStorage, what I want to do is give the user the ability to remove items from this array. I have made changes to the UI based on event.target.parentNode. But I want to remove the individual items based on their index from localStorage. Do I need to use indexOfor forEach. My current code does not work, I don't think I have to split the array, so I can access individual items as it is already an array? the function is below - any idea's?
function removeItemsLocalStorage() {
const listUl = domElements.app.querySelector('.saveUl');
listUl.addEventListener('click', (event) => {
if (event.target.tagName == 'BUTTON') {
// below tis to remove the element from the DOM, works ok.
let li = event.target.parentNode;
let ul = li.parentNode;
ul.removeChild(li);
//The code below seems abit iffy to me? as its here I am trying to remove from the index of the array
let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
let ele = displayItems.split(",");
var index = ele.indexOf(1);
ele.splice(index, 1);
}
});
}
localstorage array is like:
["Monday", "Tuesday", "Wednesday"]
Saving to localStorage
function saveItems(ele) {
localStorage.setItem('Shopping List', JSON.stringify(ele));
let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
domElements.saveList.innerHTML = displayArray(displayItems);
}
saveButton.addEventListener('click', function () {
saveItems(data);
});
Error when clicking on the removeItemsLocalStorage() function:
Uncaught TypeError: displayItems.split is not a function
function saveItems(ele) { localStorage.setItem('Shopping List', JSON.stringify(ele)); let displayItems = JSON.parse(localStorage.getItem("Shopping List")); domElements.saveList.innerHTML = displayArray(displayItems); }JSON.stringifyandJSON.parse. It's not clear whateleis in yoursaveItemsfunction. If it's an array of strings, you're set; once you remove the item, just pass the array (sans item) tosaveItems. To get the index, use the answers to Javascript - Get position of the element of the array