Local Storage is part of the HTML5 APIs - it is an object and we can access this object and its functionality via JavaScript. During this tutorial, we will use JavaScript to take a look at the fundamentals of the local storage object and how we can store and retrieve data, client side.
Local storage items are set in key/value pairs, so for every item that we wish to store on the client (the end user’s device), we need a key—this key should be directly related to the data that it is stored alongside.
There are multiple methods and an important property that we have access to, so let’s get started.
You would type this code into a HTML5 document, inside your script tags.
Setting Items
First up, we have the setItem() method, which takes our key/ value (or sometimes referred to as name/ value) pair as an argument. This method is very important, as it will allow us to actually store the data on the client; this method has no specific return value. The setItem() method looks just like this:
localStorage.setItem("Name", "Vamsi");
Getting Items
Now that we have had a look at storing some data, let’s get some of that defined data out of local storage. To do this, we have the getItem() method, which takes a key as an argument and returns the string value that is associated with it:
localStorage.getItem("Name");
Removing items
Another method of interest to us is the removeItem() method. This method will remove Items from local storage (we will talk a little more about ‘emptying’ local storage later). The removeItem() method takes a key as an argument and will remove the value associated with that key. It looks just like this:
localStorage.removeItem("Name");
Here is the sample example.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Local Storage</title>
<script>
localStorage.setItem("Name", "Vamsi");
localStorage.setItem("Job", "Developer");
localStorage.setItem("Address", "123 html5 street");
localStorage.setItem("Phone", "0123456789");
console.log(localStorage.length);
console.log(localStorage.getItem("Name"));
localStorage.clear();
console.log(localStorage.length);
</script>
</head>
<body>
</body>
</html>