Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing JavaScript in the <head>, getElementById returns null

Tags:

javascript

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

like image 337
crab Avatar asked Apr 18 '11 15:04

crab


People also ask

Why is getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What does getElementById return JavaScript?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What result will the JavaScript function document getElementById return if it is executed before the DOM is ready?

That means that any call to a DOM element which occurs before that DOM element appears in the HTML, will fail. The div appears after the script . At the moment the script is executed, the element does not exist yet and getElementById will return null .


2 Answers

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');
};
like image 107
Alnitak Avatar answered Oct 04 '22 18:10

Alnitak


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.
like image 35
Zach Rattner Avatar answered Oct 04 '22 19:10

Zach Rattner