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);

    }
parul71625
  • 193
  • 2
  • 4
  • 14

1 Answers1

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>
user3297291
  • 22,592
  • 4
  • 29
  • 45