Joseph U.
Joseph U.

Reputation: 4607

How do I get the key value when retrieving local storage

I am using HTML5 and local storage to set / retrieve key/value pairs.

To set the value:

localStorage.setItem("003o000000BTRXz", "MyValue");

Then I utilized a function to loop through all stored items

for(var i = 0; i < localStorage.length; i++) {
  var obj = localStorage.getItem(localStorage.key(i));
  alert(obj);
}

The result is "MyValue" and I would like it to be "003o000000BTRXz".

What would be the proper syntax to get this?

Upvotes: 1

Views: 3730

Answers (2)

Lakmal Caldera
Lakmal Caldera

Reputation: 1031

All browsers, especially the old ones might sometimes not support localstorage api included in HTML5. Thus it is advisable to first check if your browser supports it like so,

if(typeof(Storage) !== "undefined") {
// Have fun with localstorage! :)
} else {
// alert something saying doesn't support
}

Use the localstorage api like so,

// Store
localStorage.setItem("key", "Value");
// Retrieve
localStorage.getItem("key");

Upvotes: 1

David Sherret
David Sherret

Reputation: 106630

Use localStorage.key(i) to get the key:

for (var i = 0; i < localStorage.length; i++) {
    var key   = localStorage.key(i);
    var value = localStorage.getItem(key);

    alert(key + ": " + value);
}

Upvotes: 3

Related Questions