Javascript – document.getElementById fails in a function

javascript

I have encountered odd behavior when using document.getElementById tonight. Duplicated in Firefox 3 and Safari.

Basically, it finds the div with id "divid" in Example1. However, in Example2 it always returns null. What's going on here?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<script type="text/javascript">

addelement = function(){
    alert( document.getElementById('divid') );  
}

//Example1
window.onload = function(){ alert( document.getElementById('divid') ); }
//Example2
window.onload = addelement();

</script>
<body>

    <div id="divid" class="divclass">
        <p>Test</p>
    </div>

<body>

</html>

Best Solution

When you write this line:

window.onload = addelement();

...you are not actually assigning addelement to window.onload. You are executing addelement, then assigning the result to window.onload.

Change the line to this:

window.onload = addelement;