Open In App

HTML DOM Local Storage clear() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The clear() method removes all the Storage Object items for the current domain. 

Syntax:

localStorage.clear()

Property Values: No Property Values 

Example: Set item, clear, and display for the current domain. 

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        body {
            text-align: center;
        }
         
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <h2>HTML DOM Storage clear() Method</h2>
 
    <p>
      Example to demonstrate the use of storage
      clear() method to delete all the local
      storage items for this domain.
    </p>
 
    <p>
      Script to create some local storage items.
      Click the button to create the items:
    </p>
 
    <button onclick="createItems()">
        Create local storage items
    </button>
 
    <h2>Display Items</h2>
 
    <p>
      Click the button to display all the items:
    </p>
 
    <button onclick="displayItems()">
      Display items
    </button>
    <p id="demo"></p>
 
    <h2>Remove Items</h2>
 
    <p>
      Click the button to clear the storage:
    </p>
 
    <button onclick="deleteItems()">
      Clear
    </button>
 
    <h2>Display Items Again</h2>
 
    <p>
      Click the button to display all the items:
    </p>
 
    <button onclick="displayItems()">
      Display again
    </button>
    <p id="demo"></p>
 
    <script>
        function createItems() {
 
            // Set item in local storage.
            localStorage.setItem("GeeksForGeeks", "");
            localStorage.setItem("HTML DOM", "");
            localStorage.setItem("Storage Clear() Method", "");
        }
 
        function deleteItems() {
            // Clear local storage items.
            localStorage.clear();
        }
 
        function displayItems() {
            var l, i;
            // Display items.
            document.getElementById("demo").innerHTML = "";
            for (i = 0; i < localStorage.length; i++) {
                x = localStorage.key(i);
                document.getElementById("demo").innerHTML += x;
            }
        }
    </script>
 
</body>
 
</html>


Output: 

 

Supported Browsers: The browser supported by DOM Local Storage clear() are listed below:

  • Google Chrome 4.0
  • Edge 12.0
  • Internet Explorer 8.0
  • Mozilla Firefox 3.5
  • Opera 10.5
  • Safari 4.0


Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads