Reloading a page will display [object CSSStyleDeclaration]

Upon editing content and saving changes, instead of displaying my updated content when refreshing the page, it shows [object CSSStyleDeclaration].

function newElement() {
  let li = document.createElement("li");
  let inputvalue = document.querySelector("#myInput").value;
  let savedNote = document.createTextNode(inputvalue);
  li.appendChild(savedNote);
  if (inputvalue === '') {
    alert("Please write something")
  } else {
    document.querySelector("#myNotes").appendChild(li);
  }
  document.querySelector("#myInput").value = '';
}

function saveEdits() {
  let editElement = document.querySelector("#saved-notes");
  editElement = document.querySelector("#myNotes");
  let userVersion = editElement.innerHTML;
  userVersion = editElement.style;
  localStorage.userEdits = userVersion;
  document.querySelector("#update").innerHTML = "Edits saved. Refresh the page to see changed content";
}

function checkEdits() {
  if (localStorage.userEdits != null)
    document.querySelector("#saved-notes").innerHTML = localStorage.userEdits;
  document.querySelector("#myNotes").style = localStorage.userEdits;
}
ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;
}
<html>

<head>
  <meta charset="utf-8">
</head>

<body onload="checkEdits()">

  <div id="myDiv" class="new-note">
    <textarea id="myInput"></textarea><br>
    <button onclick="newElement()" class="save-button">Create</button>
    <button onclick="saveEdits()" class="edit-button">Save Changes</button>
  </div>

  <div id="update"></div>
  <div id="saved-notes"></div>
  <ul id="myNotes">
  </ul>

</body>

</html>

If I remove userVersion = editElement.style;, the CSS styles are lost and only plain text is displayed.

I am seeking to understand why this issue occurs and how to resolve it. Thank you in advance for your assistance.

Answer №1

The reason is that the Function localStorage.set can only save Strings, so it will call .toString() on the Object before storing it. This results in the type being saved as [object CSSStyleDeclaration]. Have you considered converting it to a string before saving it?

userVersion = JSON.stringify(editElement.style);
document.querySelector("#myNotes").style = JSON.parse(localStorage.userEdits);

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

The rationale behind organizing analogous variables into groups

Currently, I am grappling with determining the optimal logic for grouping parameters within a specified tolerance level. Let me illustrate this with an example... Task1: parameter1=140 Task2: parameter1=137 Task3: parameter1=142 Task4: parameter1=139 Task ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

I'm struggling to understand the purpose of using response.on

I have a code snippet here and I am curious about the functionality of "response.on" and why we are passing "data". What does this "data" represent? Also, could you explain what ".on" is specifically used for in this context? const express = require("exp ...

I am trying to display my progress bar in a col-sm-6 format on screens larger than 546px, however, despite my attempts, I am not seeing any changes on the screen

Is there an alternative method if bootstrap is unable to handle this? I have used col-xs-6, but all I want is to display my progress bar in the image shown on small screens. Here is how I want to display my image on small screens. <div class="cont ...

Discover the power of EJS embedded within HTML attributes!

There are two cases in which I am attempting to use an EJS tag within an HTML attribute. SITUATION 1: <input style="background-image: url(<%= img.URL %>)" /> SITUATION 2: <input onchange="handleCheckboxChange(<%= i ...

Guidelines for linking a promise function to a JSX component

How can we use React components to handle the result of a promise function and map it to JSX components? <Promise on={myFunc}> <Pending> ... </Pending> <Resolved> {(data: any) => ( ... )} ...

Creating a circular shape that adjusts to different screen sizes using only CSS

Is there a way to create perfect circles using only CSS without them turning into ovals when using percentage values for height? ...

Using Jquery and CSS to create a sleek animation for opening a div box container

Designed an animation to reveal a div container box, but it did not meet the desired criteria. Expectations: Initiate animation horizontally from 0% to 100%. Then expand vertically to 100% height. The horizontal animation from 0% to 100% is not visible ...

PHP code that generates a drop-down list using a foreach iteration

all I'm encountering a slight issue with trying to create a dynamic drop down list. Here's the code I've written: <select name='categoryID' > <?php foreach( $categories as $category)?> <option value="<?p ...

Use Javascript's JQuery library to apply functionality to a newly inserted and cloned

I am facing an issue while trying to implement JQueryUI's DatePicker on a node. It works perfectly fine for all the existing nodes, but when I use the clone function to add new nodes, it doesn't seem to apply as expected. Here is the function th ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows: <ul class="page-sidebar-menu"> <li class="menu"> <a href=""> <span class="title">Menu Item</span> <span class="arrow"></span> < ...

Problems with form functionality in React component using Material UI

Trying to set up a signup form for a web-app and encountering some issues. Using hooks in a function to render the signup page, which is routed from the login page. Currently, everything works fine when returning HTML directly from the function (signup), ...

The utilization of the "notFound" prop within getStaticProps does not influence the HTTP status code returned by the page

I recently set up a fresh Next.js application and created the following page: // /pages/articles/[slug].js import React from 'react' import { useRouter } from 'next/router' import ErrorPage from 'next/error' const Article = ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...

Searching for partial nodes

I came across a helpful tutorial that explains how to perform a partial search. My goal is to have it so that when someone enters the text geor, it can locate a user named george. db.stores.find({storeName : {$regex : /Geor/}}).pretty() However, I am str ...

"Upon refreshing the Angular app, the index.html file is not loaded

My angular.js application has a basic setup where the index.html file renders static content like Top/Sidebar. Inside, there is a <div ng-view></div> to display partial html files such as home.html. Upon logging into the application, both the ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...