In this Javascript Local storage example we will cover how to store and retrieve data from local storage. What is local storage? Local storage properties allows user to store data in key value pairs in the web browser. This local storage object stores the data without expiration date. This local storage data will not be deleted when we close the window. This local storage will be a read only property.
Let's check simple Javascript local storage example
Create simple html file which contains a input fields to enter key and values and one button to save the data.
Javascript Local Storage
|
How to store data in Local Storage?
To store data on Local Storage browser we need to use localStorage object. To store the each data item we need to pass key and value to the setItem() method.
localStorage.setItem(key,value) |
How to fetch data from Local Storage?
To fetch the data from the local storage first we need to fetch all keys first then fetch the values by passing the key to localStorage.getItem(key) method.
for(let k=0;k { } |
How to delete data from Local Storage?
To delete the specific key item data from the local storage we will use localStorage.removeItem(key) method by passing the key name.
localStorage.removeItem("key Name") |
Complete example
<html> <style> <fieldset> </fieldset> <fieldset> </div> <script> const keyinp=document.getElementById("key"); btninp.onclick=function(){ const key=keyinp.value; console.log(key); localStorage.setItem(key,value); } } for(let k=0;k<localStorage.length;k++) } |
Conclusion: In this example we learned how to store data in local storage in javscript, and retrieve and delete data from local storage object.
Article Contributed By :
|
|
|
|
4704 Views |