What is the best way to save <div> tags to localStorage?

Currently, I am facing an issue with setting an array of items (divs) to Local Storage. My intention is for these elements to be displayed in the Ui when the page reloads. The function I have written checks if there is already an array stored with that name. If it exists, the local storage needs to be cleared before updating the array with new items added in another part of the code. However, when I check what local storage is returning after setting this array, I find an array filled with empty objects of the same length instead of the expected values. Strangely, just before setting the array, all the items are present as they should be. What could I possibly be missing?

function setToLocalStorage(){
  console.log(items); //the array is correctly populated with all items

  if(!!localStorage.getItem("items")){
    localStorage.removeItem("items");
  }

  localStorage.setItem("items",JSON.stringify(items));

}

function getDataFromLocalStorage(){
  let elements=JSON.parse(localStorage.getItem('items'));
  console.log(elements); //An array of empty objects is returned with matching length

}

Answer №1

Storing an array of items (divs) in Local Storage

The localStorage function works well, but the challenge arises when attempting to JSON-serialize a DOM element.

For instance, consider this code snippet:

let el = document.createElement('div');
el.textContent = "Test";
console.log('element:', el);
console.log('element to JSON:', JSON.stringify(el));
 

This will result in the following output:

element: <div>​Test​</div>​
element to JSON: {}

To successfully store these DIVs in Local Storage, you must apply JSON.stringify to the actual data used to create them.

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

To retrieve a property in Vue, you can use either the "this" keyword

Exploring Vue for the first time and navigating through accessing viewmodel data has me puzzled. When should I utilize this.property versus vm.$data.property. In this scenario with a table where I can select rows, there are methods in place to select all ...

Endless loading with Restangular

Currently, I am using a Restangular collection which is functioning perfectly: $scope.threads = Restangular.all('thread').getList({ limit: 10, offset: 0 }).$object; However, my goal is to enhance the functionality by implementing a feature wher ...

Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3 In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one. <div class="col text-center" ng-repeat="event in weekDay.events"> &nbsp;& ...

When utilizing the useLocation feature of React-Router-DOM to retrieve data passed in React, it can cause manually inputted links to malfunction

When manually inputting a link that is incorrect (e.g., "/characters/test"), it initially works fine, but if the link is correct, it still redirects to error 404. However, clicking the link from the Character component functions properly. This me ...

How to insert space after every item generated by ng-repeat in AngularJS

I'm looking to evenly distribute elements based on this inquiry How to distribute li elements equally? I am utilizing angular with jade: ul li(ng-repeat="item in items") {{item.name}} However, ng-repeat does not create newlines after each element ...

Comparing identical elements in JavaScript

Crucial Note I want to clarify that I have no intentions of scamming, phishing, or causing any harm. My goal is to develop a website magnifier similar to using a magnifier on paper. Dilemma Let me paint the picture for you. I've effectively copied ...

Is the radio functionality and dropdown menu experiencing technical difficulties?

I'm having issues with my code, specifically in the JS function when I try to retrieve values from radio buttons and dropdown menus. Can someone help me figure out what's going wrong? CSS: #mytable { width:400px; border: 1pt solid blac ...

Tips for delivering exceptional service at the module level:

I've been working on implementing a provider for a library module that triggers my factory provider when added. However, I've encountered an issue where the provider doesn't seem to execute the console.log, indicating that it's not runn ...

Using Three.js to Project Objects onto a Plane that is Perpendicular to the Camera Orientation

I have a basic setup in Three.js involving some planes. Currently, when clicked, the planes move to random positions. Instead of the random movement, I want the planes to transition into a new grid that is perpendicular to the camera, aligning the project ...

Running automated tests using Selenium and Cucumber with JavaScript in a web browser

Hello there! I'm fairly new to this whole process. My primary goal right now is to successfully run a basic cucumber example that can automate a simple task. This will help me understand how to expand my automated testing skills to more complex scenar ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

"Encountering an issue where ng-repeat doesn't reflect updates after adding a new value to the array. Attempted to use $scope.$

Whenever the chat is opened and a name is clicked, it triggers $scope.openChat(user) which adds a name to the $scope.chat.openChats array. The ng-repeat is supposed to monitor this array for any new values but does not update. I attempted using $scope.$app ...

Is it safe to set content type as text/plain instead of application/json for JSON response?

I've been developing a PHP script to retrieve public JSON data, which will be accessed by JavaScript on the client side. However, I've encountered an issue with the server (LiteSpeed shared hosting) not having brotli/gzip compression enabled for ...

Navigate to a unique component

I am attempting to navigate to the location of a custom component, but the reference to it is not returning a valid HTML node. The function "goToContactUs" should execute this action. What would be the most effective approach to accomplish this? class H ...

Tips for properly formatting a Map<Entity,integer> within a json payload

I'm currently working on sending an entity named "order" from a client to the Rest/Api Spring Boot Back-End. Within my OrderEntity, there is a Map containing the products of that order. We are using Postman software to create a correct JSON string th ...

How to Convert Irregular Timestamps in Node.js?

Currently, I am utilizing an API to retrieve information from Google News and proceed to save the data in Firestore. The challenge lies in the fact that the API delivers timestamps in various formats which are not uniform. For example: "1 Day Ago", "June ...