HTML | DOM Window localStorage Properties

HTML DOM Window localStorage Properties allow you to store value pairs in web browsers using objects. It is a read-only property. This object is not expired even if the browser is closed. So, the data is never lost.

Syntax:

    window.localStorage
  • SAVING data to localStorage using:

    localStorage.setItem("key", "value");
  • READING data from localStorage using:

    var name = localStorage.getItem("key");
  • REMOVING data from localStorage using:



    localStorage.removeItem("key");

Example-1: Save, Read and Remove data to localStorage

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>localstorage</title>
  
    <script>
        
        //saving data locally
        function save() 
        {
            var fieldValue = 
             document.getElementById('textfield').value;
            
            localStorage.setItem('text', fieldValue);
        }
  
        
        //reading data
        function get() 
        {
            var storedValue = localStorage.getItem('text');
            if (storedValue) {
                
                document.getElementById(
                  'textfield').value = storedValue;
            }
        }
  
        
        //removing stored data
        function remove() 
        {
            document.getElementById(
              'textfield').value = '';
            
            localStorage.removeItem('text');
        }
    </script>
</head>
  
<body onload="get()">
    <p1>Type something in the text field 
      and It will Get stored locally by Browser
        <br>
        
    </p1>
    <input type="text" 
           id="textfield" />
    
    <input type="button"
           value="save" 
           onclick="save()" />
    
    <input type="button" 
           value="clear"
           onclick="remove()" />
    
    <p2>
        <br>when you reopen or reload this page,your text is still there.</p2>
    <p3>
        <br>click on clear to remove it.</p3>
</body>
  
</html>

chevron_right


Output: