HTML DOM Storage setItem() method

The HTML DOM Storage setItem() method is used to create or update a key-value pair in web storage. This method stores data in either localStorage (persistent across browser sessions) or sessionStorage (temporary for the current session) by specifying a key name and its corresponding value.

Syntax

Following is the syntax for the Storage setItem() method −

localStorage.setItem(keyname, value);

OR

sessionStorage.setItem(keyname, value);

Parameters

The setItem() method accepts two parameters −

  • keyname − A string representing the key name under which the data will be stored.

  • value − The value to be stored. This can be a string or any data type that will be converted to a string.

Return Value

The setItem() method does not return any value. It simply stores the key-value pair in the specified storage object.

Basic Example − Creating Storage Items

Following example demonstrates how to use the setItem() method to store data −

<!DOCTYPE html>
<html>
<head>
   <title>Storage setItem() Method</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; text-align: center;">
   <h2>Storage setItem() Method Example</h2>
   <p>Create localStorage item by clicking the below button</p>
   <button onclick="itemCreate()" style="padding: 10px 20px; margin: 5px;">CREATE</button>
   <p>Display localStorage item by clicking the below button</p>
   <button onclick="itemShow()" style="padding: 10px 20px; margin: 5px;">DISPLAY</button>
   <p id="output" style="margin-top: 20px; font-weight: bold;"></p>
   
   <script>
      function itemCreate() {
         localStorage.setItem("TEXT1", "HELLO WORLD");
         document.getElementById("output").innerHTML = "The key-value pair has been created";
      }
      
      function itemShow() {
         var value = localStorage.getItem("TEXT1");
         document.getElementById("output").innerHTML = "The 'TEXT1' key value is: " + value;
      }
   </script>
</body>
</html>

The output shows buttons to create and display localStorage items −

Storage setItem() Method Example
Create localStorage item by clicking the below button
[CREATE]
Display localStorage item by clicking the below button  
[DISPLAY]

(After clicking CREATE: "The key-value pair has been created")
(After clicking DISPLAY: "The 'TEXT1' key value is: HELLO WORLD")

Example − localStorage vs sessionStorage

Following example shows the difference between localStorage and sessionStorage −

<!DOCTYPE html>
<html>
<head>
   <title>localStorage vs sessionStorage</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Storage Comparison Example</h2>
   <button onclick="setLocalStorage()" style="padding: 8px 16px; margin: 5px;">Set localStorage</button>
   <button onclick="setSessionStorage()" style="padding: 8px 16px; margin: 5px;">Set sessionStorage</button>
   <button onclick="displayBoth()" style="padding: 8px 16px; margin: 5px;">Display Both</button>
   <div id="results" style="margin-top: 15px; padding: 10px; background: #f5f5f5;"></div>
   
   <script>
      function setLocalStorage() {
         localStorage.setItem("username", "John Doe");
         localStorage.setItem("theme", "dark-mode");
         document.getElementById("results").innerHTML = "localStorage items set successfully!";
      }
      
      function setSessionStorage() {
         sessionStorage.setItem("currentPage", "tutorial");
         sessionStorage.setItem("scrollPosition", "150px");
         document.getElementById("results").innerHTML = "sessionStorage items set successfully!";
      }
      
      function displayBoth() {
         var localUser = localStorage.getItem("username") || "Not set";
         var localTheme = localStorage.getItem("theme") || "Not set";
         var sessionPage = sessionStorage.getItem("currentPage") || "Not set";
         var sessionScroll = sessionStorage.getItem("scrollPosition") || "Not set";
         
         document.getElementById("results").innerHTML = 
            "<strong>localStorage:</strong><br>" +
            "username: " + localUser + "<br>" +
            "theme: " + localTheme + "<br><br>" +
            "<strong>sessionStorage:</strong><br>" +
            "currentPage: " + sessionPage + "<br>" +
            "scrollPosition: " + sessionScroll;
      }
   </script>
</body>
</html>

This example demonstrates storing different types of data in both storage types and retrieving them.

Example − Updating Existing Values

The setItem() method can also update existing keys with new values −

<!DOCTYPE html>
<html>
<head>
   <title>Updating Storage Values</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Updating Storage Values</h2>
   <p>Counter: <span id="counter">0</span></p>
   <button onclick="incrementCounter()" style="padding: 8px 16px; margin: 5px;">Increment</button>
   <button onclick="resetCounter()" style="padding: 8px 16px; margin: 5px;">Reset</button>
   <button onclick="loadCounter()" style="padding: 8px 16px; margin: 5px;">Load Saved</button>
   
   <script>
      // Load counter on page load
      window.onload = function() {
         loadCounter();
      };
      
      function incrementCounter() {
         var currentCount = localStorage.getItem("counter") || "0";
         var newCount = parseInt(currentCount) + 1;
         localStorage.setItem("counter", newCount.toString());
         document.getElementById("counter").textContent = newCount;
      }
      
      function resetCounter() {
         localStorage.setItem("counter", "0");
         document.getElementById("counter").textContent = "0";
      }
      
      function loadCounter() {
         var savedCount = localStorage.getItem("counter") || "0";
         document.getElementById("counter").textContent = savedCount;
      }
   </script>
</body>
</html>

This example shows how setItem() overwrites existing values when the same key is used multiple times.

Key Points

  • Data Persistence − localStorage data persists until explicitly cleared, while sessionStorage data expires when the browser tab is closed.

  • String Conversion − All values are automatically converted to strings. Use JSON.stringify() for complex objects.

  • Storage Limit − Most browsers allow 5-10MB of storage per domain.

  • Same-Origin Policy − Storage is accessible only within the same protocol, domain, and port.

  • Overwrite Behavior − Using setItem() with an existing key overwrites the previous value.

Conclusion

The setItem() method is essential for client-side data storage in web applications. It allows you to store key-value pairs in either localStorage for persistent data or sessionStorage for temporary session data. The method automatically converts values to strings and overwrites existing keys when called multiple times with the same key name.

Updated on: 2026-03-16T21:38:54+05:30

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements