Issue
I want to use the localStorage to save an Object which contains HTML-Clones.
var myObject["test"] = document.getElementByID("someElement").cloneNode(true);
myObject["test2"] = document.getElementByID("someOtherElement").cloneNode(true);
localStorage.saveObject = JSON.stringify(myObject);
But the Object saveObject still equals {}. It seems, that stringify can't stringify an HTML Node and if, in any way, I happen to solve the problem to save it, is it possible to parse this Object back to an HTML node?
Someone knows a solution?
Solution
Your node references will be removed from the stringified object because JSON, by definition, cannot contain functions or node references - only primitives or sub-arrays/objects. In other words, there's no way you can keep references to nodes in your local storage. You would instead need to log references to them by ID, class or some other means.
[EDIT, in response to OP's comment]
JSON and JS objects are not the same thing. The former is derived from the latter, but they are not the same. JSON is a storage means, and so cannot contain references to anything dynamic. HTML elements do not exist permanently; they exist as runtime (DOM) concepts that disappear once the page is left. Thus, they cannot be stored in any meaningful way.
JSON is therefore able to store only primitive data - strings, numbers and booleans - along with structures that allow it to nest - arrays and sub-JSON definitions.
So what happens when you run stringify
on your object is the unsuitable parts are stripped out. In your case, that's both properties. So instead, you need to store references to the elements in a more permanent, revisitable format - by ID or class, or some other reminder mechanism.
var obj = {el1: '#some_element', el2: '.some_other_element'};
localStorage.saveObject = JSON.stringify(obj);
There I save my two elements as references to their IDs (first) and class (second).
Then, when you come to reload your local storage, you look up the elements based on those factors, by feeding them, for example, to a jQuery selector.
Answered By - Mitya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.