0

So I'm working on a little personal project and I came upon a problem.

I need each day object to hold various dom element objects. These object instances are stored in an array and then that array needs to be stored into localStorage to load later.

The problem is when I do JSON.stringify and then JSON.parse it converts the HTML nodes into objects. So when I try to append element it tells me that the first parameter is not a node.

function save() {

        localStorage.days = JSON.stringify(global.days); 
        localStorage.numberOfDays = global.numberOfDays;
        localStorage.totalCount = global.totalCount;

    }

    function load() {

        var parsedDays = JSON.parse(localStorage.days);
        parsedDays.forEach(function(day){

            document.getElementById("mainPage").appendChild(day.textObject);

        });

anyone know how I can put an array of objects which hold elements into localStorage while keeping their node type????

user3628468
  • 111
  • 1
  • 7
  • Can not be done. You wiill have to re create the nodes from data you store in the JSON. Not that hard to do, and you will only have to store the relevant info – Blindman67 Sep 01 '15 at 12:32
  • you cannot serialize dom elements directly, take a look here: http://stackoverflow.com/questions/2303713/how-to-serialize-dom-node-to-json – Lorenzo Marcon Sep 01 '15 at 12:33
  • You should not serialize the DOM Element and save into localStorage. Instead, you can save your real data json into localStorage and convert to HTML when you need. – cuixiping Dec 12 '15 at 10:44

3 Answers3

1

If you will try to stringify dom nodes then it will return "{}".So its not possible to store node as it is inside localstorage.

What you can do is store information regarding nodes inside localstorage and recreate your node from that information and add it in your dom.

Juned Lanja
  • 1,466
  • 10
  • 21
0

You'd probably need to have a property eg 'type' that defines the element type

var elem

parsedDays.forEach(function(day){

   elem = document.getElementById("mainPage").createElement(day.type);
   elem.attributes = day.attributes;
   elem.innerHTML = day.textObject;

    });

Or something like that, not too sure without seeing your day object

andrew
  • 9,313
  • 7
  • 30
  • 61
0

Use JSON.stringify and JSON.parse

Example Code:

Element.prototype.toJSON = function (){
    return {nodeType:this.nodeType, outerHTML:this.outerHTML};
};
function replacer(k,v){
    if(v.nodeType===1 && v.outerHTML){
        var ele = document.createElement('html');
        ele.innerHTML = v.outerHTML;
        return ele.removeChild(ele.firstChild);
    }
    return v;
}

//test
var jstr = JSON.stringify({ele:document.body});
var json = JSON.parse(jstr,replacer);
console.log(jstr);
console.log(json);
cuixiping
  • 24,167
  • 8
  • 82
  • 93