0

I have a local storage key name "A" which contains an array of table rows. When I alert the whole array it shows [object HTMLTableRowElement],[object HTMLTableRowElement]

But when I loop over the array I am not getting the object in my variable, instead I get [ only.

How to properly fetch the table row objects from the array.

Here is my code :

 if (localStorage.getItem("A") !== null) { var lArray = localStorage.getItem("A"); alert(lArray); // alerts [object HTMLTableRowElement],[object HTMLTableRowElement] for(var i=0 ; i < lArray.length ; i++) { alert(lArray[i]); // alerts [ } } 

And here is how I am putting the table rows in my local storage

 var favA = []; function addRow() { var tableRow = document.createElement("TR"); var trID = "Tr"; tableRow.setAttribute("id", trID); favA.push(tableRow); if (typeof(Storage) !== "undefined") { localStorage.setItem("A", favA); } 
6
  • are you stringifying before putting into storage? I don't think inserting raw objects into localStorages work Commented Nov 8, 2016 at 3:06
  • No, should I stringify the TableRow object before putting it in local storage? Commented Nov 8, 2016 at 3:07
  • 1
    see stackoverflow.com/questions/25532489/… Commented Nov 8, 2016 at 3:08
  • yep, that's what I thought. it calls the toString() method every time you trying inserting an object into the local storage Commented Nov 8, 2016 at 3:10
  • better use JSON.stringify and JSON.parse Commented Nov 8, 2016 at 3:14

1 Answer 1

0

You can't use JSON.stringify on an HTMLElement. Use .outerHTML to get the HTML string. Keep in mind these can get quite long...

Use a DocumentFragment's innerHTML or the DOM's innerHTML directly to parse the string back to an element.

var mockLocalStorage = (function mock() { var store = {}; return { getItem: function(k) { return store[k]; }, setItem: function(k, v) { store[k] = v; } } }()); var myRow = document.querySelector("tr"); var myRowStr = myRow.outerHTML; // This won't work: // JSON.stringify(myRow)) // returns "{}" var toLocalStorage = function() { mockLocalStorage.setItem("_test", myRowStr); } var fromLocalStorage = function() { document.querySelector("tbody").innerHTML += mockLocalStorage.getItem("_test"); } toLocalStorage(); fromLocalStorage();
<table> <tbody> <tr> <td>A cell</td> </tr> </tbody> </table>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.