Looping through localStorage in HTML5 and JavaScript

Solution 1:

You can use the key method. localStorage.key(index) returns the indexth key (the order is implementation-defined but constant until you add or remove keys).

for (var i = 0; i < localStorage.length; i++){
    $('body').append(localStorage.getItem(localStorage.key(i)));
}

If the order matters, you could store a JSON-serialized array:

localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));

The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.

EDIT: To load the array, add to it, then store:

var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));

Solution 2:

The simplest way is:

Object.keys(localStorage).forEach(function(key){
   console.log(localStorage.getItem(key));
});

Solution 3:

In addition to all the other answers, you can use $.each function from the jQuery library:

$.each(localStorage, function(key, value){

  // key magic
  // value magic

});

Eventually, get the object with:

JSON.parse(localStorage.getItem(localStorage.key(key)));

Solution 4:

This works for me in Chrome:

for(var key in localStorage) {
  $('body').append(localStorage.getItem(key));
}

Solution 5:

localStorage is an Object.

We can loop through it with JavaScript for/in Statement just like any other Object.

And we will use .getItem() to access the value of each key (x).

for (x in localStorage){
    console.log(localStorage.getItem(x));
}