HTML DOM Storage getItem() method

HTMLWeb DevelopmentFront End Technology

The HTML DOM Storage getItem() method is used for obtaining a storage object by passing a given key name. It will return the key’s values and if there is no key with that given name then NULL will be returned.

Syntax

Following is the syntax for Storage getItem() method −

localStorage.getItem(keyname);

OR

sessionStorage.getItem(keyname);

Here, keyname is of type string and represents the name of the item to be obtained.

Example

Let us look at an example for the HTML DOM Storage getItem() method −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1 style="text-align:center">Storage getItem() method example</h1>
<p>Create a localStorage item with the name CLICKS to count the number of clicks on the create button by clicking the below button</p>
<button onclick="createItem()">CREATE</button>
<p>Get the CLICKS item value by clicking the below button</p>
<button onclick="showItem()">Display</button>
<p id="Sample"></p>
<script>
   var y=1;
   function createItem() {
      document.getElementById("Sample").innerHTML="localStorage Item has been created with name CLICKS";
      localStorage.visits = y;
      y++;
   }
   function showItem() {
      var x = localStorage.getItem("visits");
      document.getElementById("Sample").innerHTML = "The total no. of clicks are : "+x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

On clicking the “Display” button −

raja
Published on 20-Aug-2019 05:57:02
Advertisements