-3

Using console.log I am able to see value coming from another page, but when I am placing this value using document.getElementById('abc').innerHTML = xyz.age; it's giving me error of Uncaught TypeError: Cannot set property 'innerHTML' of null

My JS

xyz = JSON.parse(sessionStorage.getItem("details"));
document.getElementById('abc').innerHTML = xyz.age; //getting error from here
console.log(xyz.age);

Can you guyz help me out

Jason
  • 391
  • 1
  • 4
  • 14

2 Answers2

1

This example works using your code, you might be executing the script before the dom has been fully loaded? Try wrapping your code in document.addEventListener("DOMContentLoaded"):

document.addEventListener("DOMContentLoaded", function() {
  // code...
});

document.addEventListener("DOMContentLoaded", function() {
  xyz = { age: 24 }; // Mock data from localstorage
  document.getElementById('abc').innerHTML = xyz.age;
  console.log(xyz.age);
});
<div id="abc"></div>
Chase DeAnda
  • 13,160
  • 2
  • 26
  • 39
-1

The problem is not xyz, it's with document.getElementById('abc'). 'abc' cannot be found when your script is executing, either the element is not there, or the script is running before the document is ready.

If the latter, you may need to execute the script in a callback function after the document has been loaded. See https://www.w3schools.com/jsref/event_onload.asp

Ian Luo
  • 1
  • 1