We can use a pair of functions to work with your items in the storage:
function getStorageItems() {
var data = localStorage.getItem('items');
return data ? JSON.parse(data) : null;
}
function saveStorageItem(text) {
var array = getStorageItems() || [];
array.push(text);
localStorage.setItem('items', JSON.stringify(array));
}
With this functions you can save and load an array of text (the text of each li). In the storage, we save a text, this functions also convert/parse your array to a JSON text.
We can create another function to add one li item to your page:
function addItem(text, save) {
var node = document.createElement('li');
node.textContent = text;
document.getElementById('gfg').appendChild(node);
if (save !== false)
saveStorageItem(text);
}
By default, we save in the storage the text. Only if we pass save=false, we omit the save action. In this form, we can add and save an item and also only add (without saving).
Your test function, in this form, add and save the item:
function test() {
addItem("Hi");
}
And a last function to load items from storage:
function loadFromStorage() {
var array = getStorageItems();
if (array) {
for (var i = 0; i < array.length; i++)
addItem(array[i], false);
}
}
Here we use false in addItem because only want add the item, not saving again. You can invoke loadFromStorage to load your saved items.
NOTE: here I only save the text because is the only data required to create your HTML. If you need more data, I suggest you use an object and save/load this serialized object in the same way or the HTML.
tag isn't closed
– Reynadan Apr 12 '22 at 12:33