How to Edit and Remove item from sessionStorage

4.9k views Asked by At

This code to store items in sessionStorage so i want to add, edit , remove item and remove all my code worked well except remove item i don't know the reason

function clearItem () {
            for (var i = 0; i < sessionStorage.length; i++) {
                var a = sessionStorage.key(i);
                var b = sessionStorage.removeItem(a);
            }
        }

here's my code in jsfiddle

2

There are 2 answers

0
boomcode On BEST ANSWER
function clearItem () {
            for (var i = 0; i < sessionStorage.length; i++) {
                var a = sessionStorage.key(i);
                sessionStorage.removeItem(a);
            }
        }
10
Scott Marcus On

You have several problems:

  1. You have indicated that you only want to remove the phone number from sessionStorage here. In this case, there is no need to loop over sessionStorage at all. Just remove that one entry:

    sessionStorage.removeItem("number");
    
  2. In looking over the Fiddle that you provided, your code was quite disorganized and didn't make much logical sense from a "flow" perspective. I have modified it to a working version available here. The biggest issues with your code was that you are trying to loop over sessionStorage when saving and retrieving the values, when what you should have been doing is simply creating key/value pairs of data and accessing the data with the key names you've created.

Read about sessionStorage here