HTML DOM localStorage Properties

The HTML DOM localStorage property enables users to store key-value pairs in the browser's local storage for persistent data storage. Unlike session storage, localStorage data remains available until explicitly removed or cleared, even after the browser is closed and reopened.

Syntax

Following is the syntax to access localStorage −

window.localStorage

The localStorage object provides several methods for data manipulation −

  • setItem(key, value) − Stores a key-value pair in localStorage

  • getItem(key) − Retrieves the value associated with the specified key

  • removeItem(key) − Removes a specific key-value pair from localStorage

  • clear() − Removes all key-value pairs from localStorage

  • key(index) − Returns the key name at the specified index

  • length − Returns the number of items stored in localStorage

Basic localStorage Operations

Example − Storing and Retrieving Data

Following example demonstrates basic localStorage operations −

<!DOCTYPE html>
<html>
<head>
   <title>localStorage Basic Operations</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; text-align: center;">
   <h2>localStorage Basic Operations</h2>
   <input type="text" id="keyInput" placeholder="Enter key" style="margin: 5px; padding: 8px;">
   <input type="text" id="valueInput" placeholder="Enter value" style="margin: 5px; padding: 8px;">
   <br>
   <button onclick="storeData()" style="margin: 10px; padding: 10px;">Store Data</button>
   <button onclick="retrieveData()" style="margin: 10px; padding: 10px;">Retrieve Data</button>
   <button onclick="removeData()" style="margin: 10px; padding: 10px;">Remove Data</button>
   <div id="output" style="margin-top: 20px; padding: 10px; background: #f0f0f0;"></div>
   
   <script>
      function storeData() {
         const key = document.getElementById('keyInput').value;
         const value = document.getElementById('valueInput').value;
         if (key && value) {
            localStorage.setItem(key, value);
            document.getElementById('output').innerHTML = `Data stored: ${key} = ${value}`;
         } else {
            document.getElementById('output').innerHTML = 'Please enter both key and value';
         }
      }
      
      function retrieveData() {
         const key = document.getElementById('keyInput').value;
         if (key) {
            const value = localStorage.getItem(key);
            document.getElementById('output').innerHTML = value ? `Retrieved: ${key} = ${value}` : 'Key not found';
         } else {
            document.getElementById('output').innerHTML = 'Please enter a key to retrieve';
         }
      }
      
      function removeData() {
         const key = document.getElementById('keyInput').value;
         if (key) {
            localStorage.removeItem(key);
            document.getElementById('output').innerHTML = `Removed key: ${key}`;
         } else {
            document.getElementById('output').innerHTML = 'Please enter a key to remove';
         }
      }
   </script>
</body>
</html>

This example allows you to store, retrieve, and remove data from localStorage dynamically.

localStorage with Multiple Items

Example − Managing Multiple Key-Value Pairs

Following example shows how to work with multiple localStorage items −

<!DOCTYPE html>
<html>
<head>
   <title>localStorage Multiple Items</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>localStorage Management</h2>
   <div style="text-align: center; margin-bottom: 20px;">
      <button onclick="addSampleData()" style="margin: 5px; padding: 10px;">Add Sample Data</button>
      <button onclick="displayAllItems()" style="margin: 5px; padding: 10px;">Display All Items</button>
      <button onclick="clearAll()" style="margin: 5px; padding: 10px;">Clear All</button>
   </div>
   <div id="itemList" style="background: #f9f9f9; padding: 15px; border-radius: 5px;"></div>
   
   <script>
      function addSampleData() {
         localStorage.setItem('username', 'john_doe');
         localStorage.setItem('email', 'john@example.com');
         localStorage.setItem('theme', 'dark');
         localStorage.setItem('language', 'English');
         document.getElementById('itemList').innerHTML = '<p>Sample data added successfully!</p>';
      }
      
      function displayAllItems() {
         let output = `<h3>localStorage Items (Total: ${localStorage.length})</h3>`;
         
         if (localStorage.length === 0) {
            output += '<p>No items found in localStorage</p>';
         } else {
            output += '<table border="1" style="width: 100%; border-collapse: collapse;">';
            output += '<tr><th style="padding: 8px;">Key</th><th style="padding: 8px;">Value</th></tr>';
            
            for (let i = 0; i < localStorage.length; i++) {
               const key = localStorage.key(i);
               const value = localStorage.getItem(key);
               output += `<tr><td style="padding: 8px;">${key}</td><td style="padding: 8px;">${value}</td></tr>`;
            }
            output += '</table>';
         }
         
         document.getElementById('itemList').innerHTML = output;
      }
      
      function clearAll() {
         localStorage.clear();
         document.getElementById('itemList').innerHTML = '<p>All localStorage items cleared!</p>';
      }
   </script>
</body>
</html>

This example demonstrates how to manage multiple items, display all stored data in a table format, and clear the entire localStorage.

Working with JSON Data

Since localStorage only stores strings, complex data structures like objects and arrays must be converted to JSON format before storage.

Example − Storing Objects in localStorage

<!DOCTYPE html>
<html>
<head>
   <title>localStorage with JSON</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; text-align: center;">
   <h2>Storing Objects in localStorage</h2>
   <button onclick="storeUser()" style="margin: 10px; padding: 10px;">Store User Object</button>
   <button onclick="retrieveUser()" style="margin: 10px; padding: 10px;">Retrieve User Object</button>
   <button onclick="updateUser()" style="margin: 10px; padding: 10px;">Update User Age</button>
   <div id="userDisplay" style="margin-top: 20px; padding: 15px; background: #e8f4fd; border-radius: 5px;"></div>
   
   <script>
      function storeUser() {
         const user = {
            name: 'Alice Johnson',
            age: 28,
            city: 'New York',
            hobbies: ['reading', 'swimming', 'coding']
         };
         
         localStorage.setItem('userProfile', JSON.stringify(user));
         document.getElementById('userDisplay').innerHTML = '<p>User object stored successfully!</p>';
      }
      
      function retrieveUser() {
         const userJSON = localStorage.getItem('userProfile');
         if (userJSON) {
            const user = JSON.parse(userJSON);
            const output = `
               <h3>User Profile</h3>
               <p><strong>Name:</strong> ${user.name}</p>
               <p><strong>Age:</strong> ${user.age}</p>
               <p><strong>City:</strong> ${user.city}</p>
               <p><strong>Hobbies:</strong> ${user.hobbies.join(', ')}</p>
            `;
            document.getElementById('userDisplay').innerHTML = output;
         } else {
            document.getElementById('userDisplay').innerHTML = '<p>No user data found!</p>';
         }
      }
      
      function updateUser() {
         const userJSON = localStorage.getItem('userProfile');
         if (userJSON) {
            const user = JSON.parse(userJSON);
            user.age = 29;
            localStorage.setItem('userProfile', JSON.stringify(user));
            document.getElementById('userDisplay').innerHTML = '<p>User age updated to 29!</p>';
         } else {
            document.getElementById('userDisplay').innerHTML = '<p>No user data to update!</p>';
         }
      }
   </script>
</body>
</html>

This example shows how to use JSON.stringify() to store objects and JSON.parse() to retrieve them from localStorage.

localStorage vs sessionStorage localStorage Persists until cleared Available across tabs Survives browser restart Storage limit: ~5-10MB Domain-specific sessionStorage Expires with tab close Tab-specific storage Lost on browser restart Storage limit: ~5-10MB Domain-specific

localStorage Properties and Methods

Following table summarizes all available localStorage properties and methods −

Property/Method Description Example
setItem(key, value) Stores a key-value pair localStorage.setItem('name', 'John')
getItem(key) Retrieves value by key localStorage.getItem('name')
removeItem(key) Removes a specific item localStorage.removeItem('name')
clear() Removes all items localStorage.clear()
key(index) Returns key at given index localStorage.key(0)
Updated on: 2026-03-16T21:38:54+05:30

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements