window.onload != <body onload="">

collections, javascript, onload

Solution

You're setting the function wrong:

window.onload = getSpanElements();

should be

window.onload = getSpanElements;

You're setting the onload handler to the return value of getSpanElements() at the moment.

Problem

This is rather interesting, I think. Consider following code, both the window.onload and body onload="" call the same function. However, the results are different. It appears to me that window.onload has a problem with collections. Here's the code: ``` <html> <script type="text/javascript"> window.onload = getSpanElements(); function getSpanElements(){ var collectionBoolean = document.getElementsByTagName("span")?true:false; alert( "collection exists? " + collectionBoolean + "; number of collection members: " + document.getElementsByTagName("span").length ); } </script> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> </head> <body onload="getSpanElements()"> <span> test </span> </body> ``` As you can see, both report that the collection exists, however window.onload reports that it has no members. Any ideas?

Original source