JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
Web Storage API
The Web Storage API is a syntax used for storing and retrieving data in the browser. It can easily be used.
Example
<!DOCTYPE html>
<html>
<body>
<p id=”demo”></p>
<script>
localStorage.setItem(“name”,”Host Guru”);
document.getElementById(“demo”).innerHTML = localStorage.getItem(“name”);
</script>
</body>
</html>
Output
Example
localStorage.setItem(“name”, “Host Guru”);
The getItem() Method
The localStorage.getItem() method is used to retrieve a data item from the storage.
It takes a name as a parameter.
Example
localStorage.getItem(“name”);
The sessionStorage Object
The sessionStorage object is similar to the localStorage object.
The difference is that the sessionStorage object stores data for one session.
The data is deleted as soon as the browser closes.
Example
<!DOCTYPE html>
<html>
<body>
<p id=”demo”></p>
<script>
sessionStorage.setItem(“name”,”Host Guru”);
document.getElementById(“demo”).innerHTML = sessionStorage.getItem(“name”);
</script>
</body>
</html>
Output
The setItem() Method
The sessionStorage.setItem() method is used to store a data item in storage.
It takes a name and a value as parameters:
Example
sessionStorage.setItem(“name”, “Host Guru”);
The getItem() Method
The sessionStorage.getItem() method is used to retireve a data item from the storage.
It takes a name as a parameter:
Example
sessionStorage.getItem(“name”);
Storage Object Properties and Methods
Property/Method | Description |
key(n) | Returns the name of the nth key in the storage |
length | Returns the number of data items stored in the Storage object |
getItem(keyname) | Returns the value of the specified key name |
setItem(keyname, value) | Adds that key to the storage, or update that key’s value if it already exists |
removeItem(keyname) | Removes that key from the storage |
clear() | Empty all key out of the storage |