The HTML DOM Storage key() method is used for returning the key name at a given index in a storage object. The index is passed as a parameter to key() method. The storage object can be a session object or localStorage object.
Syntax
Following is the syntax for −
Storage key() method using localStorage −
localStorage.key(index);
Storage key() method using sessionStorage −
sessionStorage.key(index);
Here, index is of type integer representing the key number that you want to get the name for.
Example
Let us look at the example for the Storage key() method −
<!DOCTYPE html> <html> <body> <h1 style="text-align:center">storage key() method example</h1> <p>Get the first object key name by clicking on the below button</p> <button onclick="keyName()">GET NAME</button> <p id="Sample"></p> <script> function keyName() { var k = localStorage.key(1); document.getElementById("Sample").innerHTML ="The key name of the second localStorage object is "+k; } </script> </body> </html>
Output
This will produce the following output −
On clicking the GET NAME button −