key() Storage Method – How to Get a Key from Web Storage
The key() method retrieves a web storage item’s name (key).
Syntax of the key()
Method
key()
accepts one required argument. Here is the syntax:
webStorageObject.key(index);
webStorageObject
represents the storage object whose key you wish to get—that is,localStorage
orsessionStorage
.index
is the only argument accepted bykey()
. It is a required integer argument specifying the index of the item whose key you wish to get.
Examples
Below are examples of the key()
method.
How to get the name of an item in session storage
- Invoke
sessionStorage
’skey()
method. - Provide the index of the item whose name you wish to get.
// Store carColor: "Pink" in the session storage:sessionStorage.setItem("carColor", "Pink");
// Store pcColor: "Yellow" in the session storage:sessionStorage.setItem("pcColor", "Yellow");
// Store laptopColor: "White" in the session storage:sessionStorage.setItem("laptopColor", "White");
// Get the name of the item at index 1:sessionStorage.key(1);
How to get the name of an item in local storage
- Invoke
localStorage
’skey()
method. - Provide the index of the item whose name you wish to get.
// Store carColor: "Pink" in the local storage:localStorage.setItem("carColor", "Pink");
// Store pcColor: "Yellow" in the local storage:localStorage.setItem("pcColor", "Yellow");
// Store laptopColor: "White" in the local storage:localStorage.setItem("laptopColor", "White");
// Get the name of the item at index 1:localStorage.key(1);