Reputation: 1
I am trying to set an item in local storage on one page using the following code:
localStorage.setItem("move1s", JSON.stringify(document.getElementById("move1").textContent));
When I try to retrieve it with the following code, it says it returns a null error:
document.getElementById("specNickname").textContent = JSON.parse(localStorage.getItem("move1s"));
This is odd because when I try doing the following, it prints out perfectly fine so clearly the key is identifiable:
console.log(localStorage.getItem("move1s"));
I know I'm using localStorage wrong but I don't know what I'm doing wrong specifically. If more code is needed to be posted please let me know. Thank you in advance.
Upvotes: 0
Views: 202
Reputation: 679
localStorage.setItem("move1s", JSON.stringify(document.getElementById("move1").textContent));
=> "Text in node"
JSON.parse needs a JSON object, not a JSON formated string. The error you should be seeing in the console is something like
Uncaught SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse (<anonymous>)
because the first character it sees is the T in Text.
You need to wrap your text to stringify in braces {}
and make it a valid JSON Object to parse back in
var move1s = {(document.getElementById("move1").textContent))}
localStorage.setItem("move1s", JSON.stringify(move1s)};
=> {"Text in node"}
Upvotes: 1
Reputation: 2368
How to use local storage if you wanted an example:
Saving
aObj = {name: "TEST",city: "LONDON"};
aJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
Retrieving
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("example").innerHTML = obj.name;
Upvotes: 1