I have this example 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 'element' is null if myFunc is a callback of document.body.onload?
If, instead, the script is inserted after the div, it works:
<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 the onload event within the handler function, should I have the entire DOM, or not? Why should I not?
The problem is that you are calling the function immediately (and assign its return value).
Assign the function instead and it will work:
document.body.onload = myFunc;
You should also use var element in 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!';
};
}
But let's not do that. It makes no sense here. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With