Geuis
Geuis

Reputation: 42277

document.getElementById fails in a function

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>

Upvotes: 3

Views: 2353

Answers (2)

Chris Burgess
Chris Burgess

Reputation: 3631

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 cbp has already given a correct answer, but the reason might not be obvious.)

Upvotes: 5

cbp
cbp

Reputation: 25628

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;

Upvotes: 16

Related Questions