<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Local Storage Example</
title
>
</
head
>
<
body
>
<
h1
>Local Storage Example</
h1
>
<
button
onclick
=
"setLocalData()"
>Set Local Data</
button
>
<
button
onclick
=
"getLocalData()"
>Get Local Data</
button
>
<
button
onclick
=
"clearLocalData()"
>Clear Local Data</
button
>
<
button
onclick
=
"getLocalLength()"
>Get Local Length</
button
>
<
button
onclick
=
"getLocalKey(0)"
>Get Local Data by Index</
button
>
<
div
id
=
"output"
></
div
>
<
script
>
// Function to append content to output
function appendToOutput(content) {
var output = document.getElementById("output");
var existingContent = output.innerHTML;
output.innerHTML = existingContent + "<
br
>" + content;
}
// Function to set data in Local Storage
function setLocalData() {
localStorage.setItem("name", "Alice");
var preferences = { theme: "light", lang: "fr" };
localStorage.setItem("preferences", JSON.stringify(preferences));
appendToOutput("Local data set: Name: Alice, Preferences: " + JSON.stringify(preferences));
}
// Function to retrieve data from Local Storage
function getLocalData() {
var name = localStorage.getItem("name");
var preferences = JSON.parse(localStorage.getItem("preferences"));
appendToOutput("Local data retrieved: Name: " + name + ", Preferences: " + JSON.stringify(preferences));
}
// Function to clear all data from Local Storage
function clearLocalData() {
localStorage.clear();
appendToOutput("Local Storage data cleared.");
}
// Function to get the length of Local Storage
function getLocalLength() {
var length = localStorage.length;
appendToOutput("Local Storage length: " + length);
}
// Function to get Local Storage data by index
function getLocalKey(index) {
var key = localStorage.key(index);
var value = localStorage.getItem(key);
appendToOutput("Key at index " + index + ": " + key + ", Value: " + value);
}
</
script
>
</
body
>
</
html
>