0

For the code structure here

var mydo=sessionStorage.getItem("action");
function to_delete(){
    var _table=document.getElementById("showTable");
    //omit
    }
window.onload=function(){
    to_delete();
    }

I get desired result. Now rewrite the code structure as below:

var mydo=sessionStorage.getItem("action");
var _table=document.getElementById("showTable");
function to_delete(){
    //omit
    }
window.onload=function(){
    to_delete();
    }

An error occur, TypeError: _table is null.
Why can't set document.getElementById to be global variable?

showkey
  • 482
  • 42
  • 140
  • 295
  • It's not about it being global. You are trying to set the variable before the element is created. That's why you need to wait for onload. – 001 Oct 20 '16 at 12:56

1 Answers1

5

In your rewrite var _table=document.getElementById("showTable"); runs before the document loads so the element does not exist.

Instead declare the global var _table; outside the function and assign to it in the load event.

Alex K.
  • 171,639
  • 30
  • 264
  • 288