views:

38

answers:

4

hello, 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

+1  A: 

Is the getElemebtById executed before the DOM is loaded? (you should wait for domready or onload)

Is it possible that you overwrite the value in some other funtion?

some
yep...the dom wasn't loaded
bogdan
declared the variable inside a function executed on onload...thanks
bogdan
@bogdan: No problem, it's a very common beginners mistake.
some
A: 

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();">
Guffa
A: 

I think the problem may be that if you declare that variable globally, when that line is evaluated the DOM is not totally loaded and therefore the element is not accessible.

When you declare it in the function, the variable will only be created when you call that function, when the DOM will mostly likely already be fully loaded.

Danilo
declared the variable inside a function executed on onload...fixed...thanks everyone!
bogdan
A: 

Maybe your page is not fully loaded when you're calling getElementById.

Make sure you create the global variable x when the page has finished loading. Most libraries has a way to handle that, jQuery for example has the "ready"-function. If you dont want to use any libraries, you can always create the variable when the body-element calls the onload-event.

jQuery-style:

$(function(){
    // create X here
})

body onload style:

<body onload="aFunctionThatCreatesYourVariable()">
Jakob