I have certain items on a page where by, when 'addToCart' is clicked, the respective item is saved in the local storage from which it is retrieved and displayed in the cart. The format with which they are sent to the local storage is cartItems={[product.title]:product} which is then stored using the line localStorage.setItem('productsInCart',JSON.stringify(cartItems)); When for instance an item called Jack Daniels 1L is tapped and consequently stored in the local storage, I get a table the that looks like below in the local storage:
Key Value
cartNumbers 1
productsInCart {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}
totalCost 3850
Once the product is displayed in the cart, there's a delete button which can be used to delete it, especially from the local storage i.e I wish to delete the following entry from the local storage {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}. Below is a function called when the delete button has been tapped that I hoped would have worked but in vain:
function removeCartItem(event){
var buttonClicked = event.target;
if (buttonClicked) {
var current = buttonClicked.parentElement.parentElement;
var title = current.querySelectorAll('.cart-item-title')[0].innerText;
var cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems)
if (cartItems) {
var itemKeys = Object.keys(cartItems);
for (var i = 0; i < itemKeys.length; i++) {
var key = itemKeys[i]
console.log(key)//in this case prints: Jack Daniels 1L, as desired.
if (title === key ) {
localStorage.removeItem(key)
}
}
}
}
}
What is the best way to proceed?
event.targetunless you really know what you're doing. Stick always toevent.currentTargetinstead. (Put i.e: a<i>inside your button and you'll see why).buttonClicked.parentElement.parentElement.parentElement....is just waiting for you to slightly modify the HTML markup to fail beautifully the JS you wrote. Use.closest()instead.data-*attributes like i.e:data-id="245"given this data:{"245": {id: "245", "title":"Jack Daniels 1L","cost":3850,"cartConts":1}}