Looping through localStorage in HTML5 and JavaScript

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));

Leave a Comment