To retrieve an element from the local storage we have to check whether the browser endorses the local storage or not. Later, we have to set an element in the local storage. At this moment we have to be careful because once the browser is closed, no data will be stored in the local storage. Later on, we need to retrieve the data that is stored in the local storage. Let's discuss it in a nutshell.
To set data in the local storage the following is the syntax
localStorage.setItem();
Example
In the following example, initially, the Compatability of the storage is checked, using if condition. Later on, using localStorage.setItem() an item is placed in the local storage. Once the item is in the local storage, using the property localStorage.getItem() the data is retrieved.
<html> <body> <p id = "storage"></p> <script> if (typeof(Storage) !== "undefined") { localStorage.setItem("product", "Tutorix"); document.getElementById("storage").innerHTML = localStorage.getItem("product"); } else { document.getElementById("storage").innerHTML = "Sorry, no Web Storage compatibility..."; } </script> </body> </html>
Output
Tutorix