Is it possible to save any additions made to the DOM using JavaScript into local storage, so that it can be retrieved even after the page is reloaded?

Let's consider a scenario for testing purposes: you have a function that appends <li> elements inside an <ol> container, and you want to retain all the list items added. Is there a way to store them in Local Storage (or any other local storage method) so they can be retrieved every time the page is reloaded?

I've looked into the Window.localStorage API but couldn't find a method to store dynamic elements like this. As a student, I might not recognize the best practice for doing this. Any ideas or suggestions?

var textcounter = 1;
var inputcounter = 1;

function addText() {
var div = document.getElementById("div");
var texttobestored =document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color="red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored =document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
div.appendChild(inputstobestored);
inputcounter++;
}
#div{
width:600px;
}
<html>
<body>
<ol id="div">
<button onclick="addText()" style="height:100px;width:100px">ADD TEXT</button>
<button onclick="addInputs()" style="height:100px;width:100px">ADD INPUTS</button>
</ol>
</body>
</html>

Answer №1

Check out this live example: https://jsfiddle.net/3ez4pq2d/

The following function, saveInput, is used to store data in local storage. It also creates inputs that are retrieved using loadInput.

This code snippet saves the ID, COLOR, and WIDTH values. You can easily expand upon this to include more fields.

function saveinput(obj) {
  saved = localStorage.getItem("items") || "[]"
  saved = JSON.parse(saved)
  saved.push(obj)
  localStorage.setItem("items", JSON.stringify(saved))
}

var textcounter = 1;
var inputcounter = 1;

function addText() {
  var div = document.getElementById("div");
  var texttobestored = document.createElement("li");
  texttobestored.id = "text" + textcounter;
  texttobestored.style.color = "red";
  texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
  div.appendChild(texttobestored);
  textcounter++;
}

function addInputs() {
  var div = document.getElementById("div");
  var inputstobestored = document.createElement("li");
  inputstobestored.id = "input" + inputcounter;
  inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
  inputstobestored.style.color = "blue";
  inputstobestored.style.width = "600px";

  saveinput({
    id: "input" + inputcounter,
    color: "blue",
    width: "600px"
  })

  div.appendChild(inputstobestored);
  inputcounter++;
}

function loadInput() {
  inputs = localStorage.getItem("items") || "[]"
  inputs = JSON.parse(inputs)

  inputs.forEach(function(input) {
    var div = document.getElementById("div");
    var inputstobestored = document.createElement("li");
    inputstobestored.id = input.id;
    inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
    inputstobestored.style.color = input.color;
    inputstobestored.style.width = input.width;
    div.appendChild(inputstobestored);
    inputcounter++;
  })
}

loadInput();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger an alert message upon loading the HTML page with search text

I need to search for specific text on a webpage and receive an alert if the text is found. <script type='text/javascript'> window.onload = function() { if ((document.documentElement.textContent || document.documentElement.innerText ...

How to relocate zeros to the end of an array using JavaScript without returning any value?

I'm currently working on a coding challenge from leetcode.com using JavaScript. I'm relatively new to algorithms and seem to be struggling with getting my initial submission accepted. The task at hand is as follows: Given an array nums, the goa ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

What steps can you take to prevent a potential crash from occurring when an unauthorized user attempts to access a page without logging in?

I've encountered an issue where the app crashes when trying to access a page that requires logging in. The reason for this crash is because the page attempts to load undefined data, resulting in the error: TypeError: Cannot read property 'firstN ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Having trouble with image hover functionality on pure CSS?

<div id="headermenu"> <ul > <li id="menu1"><a href="#"><img src="images/menu1.png"/></a></li> <li id="menu2"><a href="#"><img src="images/menu2.png"/></a> < ...

Expanding Input Field to Fill Available Space Using Bootstrap

I have developed a sample here: jsFiddle <div class="container"> <div class="row"> <div class="span6"> <ul class="thumbnails"> <li class="span4"> <div style="height:200px; position: relative" ...

How can I implement horizontal scrolling on a material-ui table containing numerous columns?

As I work with the React Material-UI framework, I am using this table example as a guide. However, I am facing an issue where my table becomes overcrowded when I have numerous columns, causing the content to be cut off. I recently came across the material ...

"Struggling with solving an error in METEOR REACT SEARCH and DISPLAY upon user input onChange? Let

Here is the input code snippet: Title: <input type="text" ref="searchTitle" onChange={this.searchTitle}/> This function handles the onChange event: searchTitle(event) { this.setState({ show_article_editable_list: <Article_Editab ...

What is the appropriate import to use when working with FontAwesomeIcon, React, and Jest?

Currently, I am working on a React website built with TypeScript and Webpack. I am using FortAwesome's react-fontawesome package to display icons. The import statement for this package is as follows: import FontAwesomeIcon from '@fortawesome/rea ...

Using jQuery to insert a div class with PHP referenced

My variable stores a color name. Here is an example: <?php $myvar = blueColour; ?> I want to apply this value to the body of an html page using jQuery: <script type="text/javascript"> jQuery(body).addClass("<?php echo $myvar; ?>"); < ...

Deciphering the Mysteries of HTTP Headers

I have been using various applications to evaluate the quality of my websites, and many of the improvements suggested relate to missing http headers. Some examples include Content-Security-Policy, Charset, etc... I decided to visit the Wikipedia page on ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Top approach for inserting Class instance into a group

I need some guidance on how to approach this issue. I am interested in creating a set of objects similar to the example below: Person P = new Person(); P.Name = 'John'; P.Surname = 'Dough'; var People = []; People.push(P); Can this b ...

Utilizing Inline Placement within Email Templates

Seeking assistance in finding an alternative method to achieve the desired functionality in an email template. Having trouble with inline position styling being removed. table { width: 80%; border-spacing: 0; } table tr td.label-dots { positio ...

Scroll through the menu with ease

I am facing an issue with my menu that has 2 levels. Whenever I try to scroll down, I want the position of the Logo to change to the bottom of the menu smoothly. However, during scrolling, there is a noticeable shake in the menu movement which makes it app ...

When a user clicks on an Ajax.ActionLink, I want to trigger a Javascript function to execute

I am using an Ajax.ActionLink() in my code. When clicked, it loads a partial view within the parent view. It works perfectly fine. Now, I need to call a JavaScript function when this Ajax.ActionLink() is clicked to enable some other functionality. I am uns ...

Eliminate the mystery overflow in your CSS styling

My website is experiencing overflow on the x axis, even though all vw/width properties are set to 100. I suspect that the .logout element may be causing this issue, but I'm not sure what exactly needs to be modified to resolve it. Any assistance would ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...