Set the value of the specified local storage item:
localStorage.setItem("mytime", Date.now());
This example demonstrates how to use the setItem()
method to set the value of a specified local storage item.
<!DOCTYPE html> <html> <body> <button onclick="createItem()">Set local storage item</button> <button onclick="readValue()">Get the item value</button> <p id="demo"></p> <script> function createItem() {//from w w w . ja va 2s .c o m localStorage.setItem("mytime", Date.now()); } function readValue() { var x = localStorage.getItem("mytime"); document.getElementById("demo").innerHTML = x; } </script> </body> </html>
The setItem()
method sets the value of the specified Storage Object item.
The setItem()
method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
setItem(keyname, value);
Parameter Values
Parameter | Description |
---|---|
keyname | Required. A String specifying the name of the key to set the value of |
value | Required. A String specifying the value of the key to set the value of |
The setItem()
method returns a String representing the inserted value.