Am trying to implement a feature where an item is to be deleted from local storage when a user clicks a button. The item is part of an array stored in local storage. However am not able to here is how the item is saved
const favBtns=meal.querySelectorAll(".fav-btn i")
const images = document.querySelectorAll('.meal-header > img')
favBtns.forEach((favBtn,i)=>{
favBtn.addEventListener("click", ()=>{
favBtn.classList.toggle("active")
console.log(images[i].src, images[i].alt)
myFavMeals.push({src: images[i].src, alt: images[i].alt})
localStorage.setItem("myFavMeals", JSON.stringify(myFavMeals))
showMeal
})
})
here is how am trying to delete the item
function clearfav(){
const clears=document.querySelectorAll("i#clear.fa.fa-window-close")
clears.forEach(clear=>{
clear.addEventListener("click",()=>{
let favmeals= JSON.parse(localStorage.getItem("myFavMeals"))
favmeals.forEach((favmeals,i)=>{
favmeals.splice(favmeals[i],1)
showMeal()
})
})
})
}
favmeals is your parsed array and also favmeals is array element inside of forEach. Rename one of them.// With [1][2]
function clearfav() {
const clears = document.querySelectorAll("i#clear.fa.fa-window-close")
clears.forEach(clear => {
clear.addEventListener("click", () => {
let favmeals = JSON.parse(localStorage.getItem("myFavMeals"))
favmeals.forEach((favmeal, i) => {
favmeals.splice(favmeals[i], 1)
showMeal()
})
localStorage.setItem("myFavMeals", JSON.stringify(favmeals))
})
})
}
forEach inside of "click" event handler at all, because now you trynna to remove each element. For example if you wanna remove only element with same index with icon you clicked on:// With [1][2][3]
function clearfav() {
const clears = document.querySelectorAll("i.fa.fa-window-close")
clears.forEach((clear, index) => {
clear.addEventListener("click", () => {
let favmeals = JSON.parse(localStorage.getItem("myFavMeals"))
favmeals.splice(index, 1)
localStorage.setItem("myFavMeals", JSON.stringify(favmeals))
})
})
}
Also should be noticed: i#clear.fa.fa-window-close is wrong query, bacause it means you have multiple elements with same id. id should be unique, use classes instead.