9

I have following code

<html>
<head>
<script language="JavaScript">

function foo(q) {
    this.run=function(color){
        var x=document.getElementById("ff");
        alert(x); // <----x=null
    };

}

var q=new foo();
q.run("yellow");
</script>
</head>
<body>

<div id="ff"></div>

</body>
</html>

does anyone has idea why x=null

3
  • 1
    See stackoverflow.com/questions/5703734/… BTW, the language attribute of the script element has been deprecated long ago. Commented Apr 18, 2011 at 15:07
  • If I got a penny for every question on SO about this issue ... :) Commented Apr 18, 2011 at 15:14
  • 2
    You should accept an answer by clicking the hollow check. Commented Apr 18, 2011 at 22:46

3 Answers 3

23

It's null because you're calling the script before the DOM has been loaded.

Wrap your script in a function which will be invoked onload, e.g.:

window.onload = function() {
    var q = new foo();
    q.run('yellow');
};
Sign up to request clarification or add additional context in comments.

Comments

1

By the time the script is parsed, only the <html> and <head> tags have been loaded. There are several ways you can fix this:

  1. Put the <script> tags at the end of your document, instead of at the beginning
  2. Put the Javascript in another file and load it in the head with <script type="text/javascript" src="OtherFile.js"></script>
  3. Wrap the entire function in window.onload = function () { yourCodeHere(); }, which will halt execution of your code until the window has loaded.

2 Comments

This is not entirely true: the DOM works with elements, not tags. That means that the head element is not yet completely inserted into the DOM and you can't reliably manipulate the head element. Moreover, (2) will not solve the issue, it doesn't matter whether you include code inline or in an external script, JavaScript scripts are executed sequentially.
Marcel, thanks for the clarification. As far as your second point goes, isn't loading a script in another file the same as running it with async=false?
1

This JS code will run before the DOM is ready so the node will not be found. To perform execution only once the DOM is ready, you could use the window.onload event handler.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.