Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage.

Unfortunately, my current code is not achieving this. How can I make it work?

To accomplish this task, I have created a JSON object that serves as an array. Each element in the array corresponds to a specific day on the calendar. I am targeting the cell (thisCell) that I click on in order to retrieve the relevant stored information.

    var organizer = [
        //February 9, 2015
        {thisCell.getElementsByClassName("spanEvent")[0].value: JSON.parse(localStorage.getItem("event")),
         thisCell.getElementsByClassName("spanDate")[0].value: JSON.parse(localStorage.getItem("date")),
         thisCell.getElementsByClassName("spanParticipants")[0].value: JSON.parse(localStorage.getItem("participants")),
         thisCell.getElementsByClassName("spanDescription")[0].value: JSON.parse(localStorage.getItem("description"))
        },

        //July 22, 2016
        {thisCell.getElementsByClassName("spanEvent")[0].value: JSON.parse(localStorage.getItem("event")),
         thisCell.getElementsByClassName("spanDate")[0].value: JSON.parse(localStorage.getItem("date")),
         thisCell.getElementsByClassName("spanParticipants")[0].value: JSON.parse(localStorage.getItem("participants")),
         thisCell.getElementsByClassName("spanDescription")[0].value: JSON.parse(localStorage.getItem("description"))
        }
      ]; 

Answer №1

It seems there may be a confusion in your understanding of how to access and modify the content of DOM elements.

The code you have written will not achieve the desired outcome because you are only creating an object, without actually accessing any properties of a DOM element. Additionally, <span> elements do not use the value property to access their content. Instead, they utilize the innerHTML property like most other HTMLElements.

Moreover, the JSON.parse(string) method is used to convert a string into a JavaScript Object{}, which might not be necessary in this case since you are attempting to assign the value to a <span>, which should be a string.

To demonstrate what I believe you are aiming for, I have prepared a fiddle.

HTML

<div class="cell"> 
 <span class="spanEvent"></span>
 <span class="spanDate"></span>
 <span class="spanParticipants"></span>
 <span class="spanDescription"></span>
</div>

JavaScript

localStorage.setItem("event", "someEv");
localStorage.setItem("date", "someDate");
localStorage.setItem("participants", "someParticipants");
localStorage.setItem("desc", "someDesc");

cell = document.querySelector(".cell");
spanEv = cell.querySelector(".spanEvent");
spanDate = cell.querySelector(".spanDate");
spanPart = cell.querySelector(".spanParticipants");
spanDesc = cell.querySelector(".spanDescription");

spanEv.innerHTML = localStorage.getItem("event");
spanDate.innerHTML = localStorage.getItem("date");
spanPart.innerHTML = localStorage.getItem("participants");
spanDesc.innerHTML = localStorage.getItem("desc");

Note: I have used the querySelector() method to select the cell and its elements, but feel free to use any preferred DOM selection technique (getElementsByClassName() is typically faster).

I hope this clarifies things for you!

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

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

What is the best way to convert a Kotlin Flow into non-streaming JSON data with the Content-Type set to application/json in Spring Framework 6?

Method interface for controlling: @RequestMapping( method = [RequestMethod.GET], value = ["/list"], produces = ["application/json"] ) suspend fun list(): ResponseEntity<Flow<MyClass>> Implementation ...

Express.js experiencing difficulty integrating with Share.js

When it comes to Server-Side code, var express = require('express'); //Web Framework var app = express(); var http = require('http').Server(app); //HTTP server module var connect = require('connect'), sharejs = require(&a ...

Child functional component does not refresh after its props are altered by its parent component

Looking at the following code: MainParentComponent.js let data = 0; function MainParentComponent() { function handleClick() { data++; } return (<> <button onClick={handleClick}>Increase</button> < ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divi ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

Running pug directly from the local node_modules directory

I'm currently attempting to run pug (/jade) from my node_modules directory, however I am unable to locate the executable within the node_modules/.bin folder. I am running MacOS 10.12.5 and installed pug using the "npm install --save pug" command. Is ...

The b-link component in bootstrap-vue is not displaying the text content or inner HTML as expected

Having trouble retrieving the textContent from a blink element and modifying it. Interestingly, when attempting the same process with a tag or div tag, it works without any issues. <b-link :ref="index" v-b-toggle="`${index}`" @c ...

Transferring information between functions

I am trying to retrieve the value of my drop-down within the getData function. Although the data displays correctly in the run function, I am unsure of how to pass that data down to the getData() function. <select class="form-co ...

Invoke Selenium using JavaScript

Imagine I have this (fictional) JavaScript snippet: asynchronousOperation.addEventListener("completed", function (event) { if (event.property == "required value") tell Selenium we are good; else tell Selenium the test failed; }); ...

Exploring the process of extracting a JSON array from HttpServletRequest

I am completely new to servlets and I'm having trouble extracting a JSON array from the HttpServletRequest This is the JSON data I'm sending to Java: page: 1 start: 0 limit: 20 sort: [{"property":"fiscalYear","direction":"DESC"}] protected vo ...

Accessing missing values in JSON with circe-optics

The JSON data I am working with is structured like this: { "cards": [ { "card_id":"1234567890", "card_status":"active", "card_expiration":{ "formatted":"01/20" }, "de ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

PHP fails to retrieve posted data from AJAX when using serializeArray()

I have been struggling with a form that is utilizing jQuery validation and AJAX to submit data to a PHP script for backend processing. The AJAX function uses serializeArray() to collect the form values, but despite my best efforts, I cannot seem to success ...

Using C# to deserialize JSON with Inheritance

Here is some code that creates an object, writes it to a file, reads from the file, and deserializes it back into the same object. The issue here is that when deserializing, the information in one of the properties is lost. internal class Program { pr ...

Adding specific key, value pairs to a python dictionary by extracting data from a json file

I am facing an issue where I need to extract a specific key and value from a JSON file in Python and add it to a dictionary. Currently, I have been able to successfully add all the data from the JSON file into my dictionary, but that is not the desired out ...

Sort through the array using a separate array in Vuejs

I am currently working with two arrays: { "products": [ { "name": "Jivi", "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche", "frequency": ["1", "2", "8"] }, { "name": "Adynovi", ...

What is the process for sending a request and obtaining a response from a REST API using JavaScript?

I have a private server set up on my computer with a built-in REST API. The base URL for the API is: . I am now looking to develop a client application for this server using the API. To authenticate on the server, the API endpoint is baseurl/login with the ...

What sets this.prototype apart from module.exports?

As a newcomer to the world of Node.js, I am eager to gather information, experiment with testing techniques, and explore the code written by others. In my exploration, I have noticed that creating and requiring modules is a common practice in Node.js. Dif ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...