HTML LocalStorage

Learn to persistently store data in the browser with the localStorage API.

LocalStorage in HTML

LocalStorage lets you save information in the user's browser, which persists even after closing the window. Let's see how it works.

What is LocalStorage?

The localStorage API allows data to be persistently stored in the user's browser. This data has no expiration date and remains available until it is manually deleted by the web application or the user.

Saving Data with setItem()

To save data, use the setItem() method. It takes two arguments: a key (as a string) and a value (also as a string). For example: localStorage.setItem('username', 'guest');

Retrieving Data with getItem()

To retrieve data, use the getItem() method with the corresponding key. If the key doesn't exist, it returns null. For example: let user = localStorage.getItem('username');

Practice Zone


Interactive Test 1: Drag & Drop

Arrastra en el orden correspondiente.


Arrastra las opciones:

localStorage.setItem('color', 'blue');
let color = localStorage.getItem('color');

Completa el código:

Save data:______
Retrieve data:______

Interactive Test 2: Fill in the Blanks

Rellena los huecos en cada casilla.

localStorage.('user', 'John');
let user = localStorage.('user');

Practice Example: Code Editor

Create a simple form with an input field and a button. When the button is clicked, save the input's value to localStorage and display a confirmation message.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Local Storage</title> </head> <body> <input type="text" id="name" placeholder="Enter your name"> <button onclick="saveName()">Save</button> <p id="result"></p> <script> function saveName() { let name = document.getElementById("name").value; localStorage.setItem("name", name); document.getElementById("result").textContent = "Name saved: " + name; } </script> </body> </html>

Knowledge Check

What is the main characteristic of localStorage?