tags:

views:

399

answers:

2

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"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<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>
+14  A: 

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;
cbp
+4  A: 

cbp has already posted the correct answer: the function "addelement()" is in javascript also an object, "addelement".

when you say,

x = addelement() ;

you assign the value returned by addelement() (in this case, the return value will be null) to the variable x.

when you say,

x = addelement ;

you assign the function addelement() to variable x.

in assigning addelement to the onload event, you want the function to be called when the event occurs. so you write it without the brackets.

window.onload = addelement ;

(just a clarification, because jorge has already given a correct answer, but the reason might not be obvious.)

Chris Burgess