Bereznyak
Bereznyak

Reputation: 75

How to read back data from LocalStorage

Once checkbox is active there are various <p> tags that get class "result". What I do with them is following:

function submit(){
  alert("in submit");
  var user_choice = document.getElementsByClassName("result");
  for (var i = 0; i < user_choice.length; i++){
    console.log(user_choice[i].innerHTML);
  }
  localStorage.setItem('storage',user_choice);
}

I hope this makes an HTMLcollection. After that, at submitted.html page (redirect there after pressing submit button) I wanna console.log all the items. So I write this:

window.onload = function() {
  if ( localStorage.getItem('storage')) {
    var got_user_choice = localStorage.getItem('storage');
    for (var i = 0; i < got_user_choice.length; i++){
      console.log(got_user_choice[i].innerHTML);
    }
 }
}

As long as it's a HTMLcollection (read array) I operate with it in terms of array. But what I get in console is just undefined. What's wrong with my code?

Upvotes: 0

Views: 66

Answers (1)

Barmar
Barmar

Reputation: 780724

Local storage can only contain strings, not DOM elements. You should make an array of all the elements, and convert that to JSON.

function submit(){
  alert("in submit");
  var user_choice = document.getElementsByClassName("result");
  var html = [];
  for (var i = 0; i < user_choice.length; i++){
    console.log(user_choice[i].innerHTML);
    html.push(user_choice[i].innerHTML);
  }
  localStorage.setItem('storage',JSON.stringify(html));
}

Upvotes: 4

Related Questions