Document.getElementById not working in function

I came across odd behavior when using document.getElementById today. Duplicated in Firefox 3 and Safari.

Basically, it finds a div with id "div" in example 1. However, in example 2, 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>
+3
source share
2 answers

When you write this line:

window.onload = addelement();

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

Change the line as follows:

window.onload = addelement;
+16
source

cbp : "addelement()" javascript , "addelement".

,

x = addelement() ;

, addelement() ( null) x.

,

x = addelement ;

addelement() x.

addelement onload , . .

window.onload = addelement ;

( , cbp , .)

+5

All Articles