Isaiah Bugarin
Isaiah Bugarin

Reputation: 493

Getting and setting style not working?

I have some code like this:

var content = document.getElementById('myDivId');

function MyFunction()
{
     alert(content.style.height);
}

For some reason, I'm not getting any message box. I have the "body onload" equal to "MyFunction()".

Upvotes: 0

Views: 49

Answers (1)

ruakh
ruakh

Reputation: 183251

You can't have

var content = document.getElementById('myDivId');

just free-floating in your script, because then it will run before the myDivId element has actually been created, so content won't end up referring to it. Try putting it inside your onload-handler:

function MyFunction()
{
      var content = document.getElementById('myDivId');
      alert(content.style.height);
}

instead; or, if you want it to be globally visible, you can at least initialize it inside your onload-handler:

var content; // declare globally

function MyFunction()
{
      content = document.getElementById('myDivId'); // initialize
      alert(content.style.height);
}

Upvotes: 2

Related Questions