Search code examples
javascriptdomvariablesscope

javascript: can not use global variable in a function, to navigate the dom


beginner here... what am i missing?

i define a global variable that is a reference to an html element:

         var x=document.getElementById("xxx1");

then, inside a function a try to reference that variable to navigate the dom:

        x.innerHTML="dsfgfdgdf";

...doesn't work; if i define the variable inside the function it works, but i don't see how it's a scope problem... working with global variables inside functions works fine IF i don't use them in a dom context (object.property)

thanks


Solution

  • It's not a scope problem.

    The most likely reason is that the element doesn't exist yet when you create the variable. You have to put the script element that creates the variable after the element that you want to access, as the code will run while the page is loading.

    Another alternative is to declare the variable globally, and set it from the onload event that runs after the page has loaded:

    <script>
    
    var x;
    
    function init() {
      x = document.getElementById('xxx1');
    }
    
    </script>
    
    <body onload="init();">