English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Storage key() method

JavaScript Storage Object

key() The method returns the name of the key with the specified index.

The key() method belongs to the storage object and can belocalStorageobject orsessionStorrageobject.

The order of the keys is determined by the user-Defined by the agent, so you should not rely on it.

Syntax:

localStorage.key(index)
sessionStorage.key(index)
var x = localStorage.key(0);
Test and See‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the key() method:

Method
key()43.511.549

Parameter value

ParameterDescription
indexAn integer representing the index of the key to be retrieved. This is an index starting from zero

Technical details

Return value:A string containing the key name. IfIndexIf not present, it returns null
DOM version:Network Storage API

More examples

The following function iterates over the local storage keys:

function displayItems() {
  var items = "";
  for(var i = 0; i < localStorage.length; i++) {
 items += localStorage.key(i) + "<br>";
  }
  document.getElementById("output").innerHTML = items;
}
Test and See‹/›

The following function traverses the local storage keys and retrieves the values set for each key:

function displayItems() {
  var items = "";
  for(var i = 0; i < localStorage.length; i++) {
 items += localStorage.key(i) + : ";
 items += localStorage.getItem(localStorage.key(i)) + "<br>";
  }
  document.getElementById("output").innerHTML = items;
}
Test and See‹/›

The following function adds two data items to the current domain's session storage and then returns the name of the first session storage item:

var x = sessionStorage.key(0);
Test and See‹/›

Related References

HTML Tutorial:Web Storage API

Window (Window) Reference:window.localStorage Property

Window (Window) Reference:window.sessionStorage Property

JavaScript Storage Object