dealtek Posted September 1, 2015 Share Posted September 1, 2015 Hi All,I'm a bit confused as to how it all works - - sometimes I set the local localStorage like:localStorage.setItem("First", "Bob");localStorage.setItem("Last", "Smith");then read on another page like:<span id="First"></span> <span id="Last"></span><script>document.getElementById('First').innerHTML = localStorage.getItem("First");document.getElementById('Last').innerHTML = localStorage.getItem("Last");</script>sometimes it shows fine and sometimes on other pages some fields are blankand other page may show error like:Uncaught TypeError: Cannot set property 'innerHTML' of nullQ: What am I doing wrong - why was there sometimes errors?- if I use = document.getElementById('Last') - but fail to have the correct span id="xxxx" - does that cause the errors?- What is the criteria for getting this to always have fields show up? Link to comment Share on other sites More sharing options...
davej Posted September 2, 2015 Share Posted September 2, 2015 Try... <script>window.onload = init;function init(){document.getElementById('First').innerHTML = localStorage.getItem("First");document.getElementById('Last').innerHTML = localStorage.getItem("Last");}</script> Link to comment Share on other sites More sharing options...
COBOLdinosaur Posted September 2, 2015 Share Posted September 2, 2015 I agree that it probably is a timing issue though I would prefer the more modern approach of: window.addEventListener('load', init,false); You are getting the error because the script is sometimes firing before the HTML parser has completed creation of the elements and their nodes in the Document Object, so when the elements are referenced they do not yest exist and are therefore null, or undefined. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now