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:
You should also use
var elementin your function to avoid creating a global variable.Or if you want to confuse people:
But let’s not do that. It makes no sense here. 😉