-4

I wanted to ask why innerHTML is not working in the following code:

document.getElementById('text').innerHTML = localStorage["mytext"];

The element with the id text is a div element. localStorage is giving me the right String if I use it with alert, what could the error be?

j08691
  • 204,283
  • 31
  • 260
  • 272
Sascha Mayr
  • 341
  • 4
  • 16

2 Answers2

1

Make sure the div exists before trying to reference it,

window.addEventListener("load",function() {
    document.getElementById('text').innerHTML = localStorage.getItem("mytext");
},false);

That will wait for the document to load before doing any modifications

lostsource
  • 21,070
  • 8
  • 66
  • 88
  • +1, you're probs right judging from the fiddle. You should change it to use `getItem` instead of accessing it via brackets, though. – Snuffleupagus Dec 03 '12 at 21:02
0

Can you check if the localStorage["text"] really returns a string? Maybe this link might help you to check the if it's really a string.

https://stackoverflow.com/a/9729103/1873758

Community
  • 1
  • 1
ipinak
  • 5,739
  • 3
  • 23
  • 41