0

Can anyone help me? I have many HTML buttons created with Javascript. I want them to delete itself on onclick and change its CSS while hovering your mouse over it, but the "newButton" variable stores the last element from localStorage, which is the last button. With my code, I can only edit the last button. I want the other buttons to delete itself on onclick and change its CSS on hover. I have tried

 newButton.onclick=function() {      
     document.getElementById("list").removeChild(newButton);
     localStorage.removeItem(newButton);
  }

but it doesn't work well. It only will remove the last button. Although it does, it doesn't remove it from local storage. By the way, the variable "list" is a < div >, not a < ul >.

Javascript

var list= document.getElementById("list");
function addItemToLocalStorage(){
    var newKey=prompt("What key do you want to add to your local storage?");
    var newItem=prompt("What value does the key have?");
    if (newKey && newItem){
        localStorage.setItem(newKey,newItem);
        location.reload();
    }
}
window.onload=function(){
    for (i=0; i<localStorage.length ; i++){
        var key=localStorage.key(i);
        var lcStorage=localStorage.getItem(key);
        var newButton= document.createElement("button");
        document.getElementById("list").insertAdjacentElement("beforeend",newButton);
        newButton.innerHTML=key+" : "+lcStorage;
        newButton.style.padding="20px";
        newButton.style.border="lightgray";
        newButton.style.fontSize="20px";
        newButton.onclick=function(){
            list.removeChild(newButton);
            localStorage.removeItem(newButton);
        }
    }
}

If you need anything else just ask me.

  • Nothing in your script tries to delete anything... [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) -> [mcve] – Andreas Mar 10 '21 at 13:49
  • @Andreas I have edited the post. Is it fine now? – SomeRandomUser101_ Mar 10 '21 at 14:19
  • The links in my comment are not just for show ;) – Andreas Mar 10 '21 at 14:20
  • For hover part you can add a class name to button and handle via CSS – kiranvj Mar 10 '21 at 14:24
  • @SomeRandomUser101_ removeItem expects a string(DOMString) as param, you are passing an object, thats why localstorage is not getting removed. And [this post](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) will help you to find why only your last button is getting deleted. – kiranvj Mar 10 '21 at 14:35

0 Answers0