JavaScript onload and DOM
I have this sample document:
<html>
<body>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
<div id="myDiv"></div>
</body>
</html>
Why is 'element' null if it myFuncis a callback document.body.onload?
If instead
<html>
<body>
<div id="myDiv"></div>
<script type="text/javascript">
document.body.onload = myFunc();
function myFunc() {
element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
}
</script>
</body>
</html>
My question is: if I use an event onloadinside a handler function, should I have the whole DOM or not? Why shouldn’t I?
The problem is that you call the function immediately (and assign its return value).
Assign a function instead, and it will work:
document.body.onload = myFunc;
You should also use var elementin your function to avoid creating a global variable.
Or if you want to confuse people:
document.body.onload = myFunc();
function myFunc() {
return function() {
var element = document.getElementById('myDiv');
element.innerHTML = 'Hello!';
};
}
. .;)