Reputation: 100
So the question is, why doesn't this append the div's on load? I'm scratching my head on this one. No errors... Just not loading.
<head>
<script type="text/javascript">
function load() {
var divTag0 = document.createElement("div");
divTag0.className = "newsBlock";
divTag0.innerHTML = " Try this..";
document.getElementById("newsLeft").appendChild(divTag0);
var divTag1 = document.createElement("div");
divTag1.className = "newsBlock";
divTag1.innerHTML = " Blah..";
document.getElementById("newsRight").appendChild(divTag1);
var divTag2 = document.createElement("div");
divTag2.className = "newsBlock";
divTag2.innerHTML = " And this ..";
document.getElementById("newsLeft").appendChild(divTag2);
}
</script>
</head>
<body>
<p> Something filler </p>
<div id="newsLeft">
</div>
<div id="newsRight">
</div>
<script type="text/javascript">
window.onload="load()";
</script>
</body>
Upvotes: 2
Views: 3502
Reputation: 92
If azhrei's answer doesn't work, the only thing I could think of would be that calling onload after it has loaded might not trigger, you can change this from your example by simply calling load();
I tested it here
Hope this helps
EDIT:
I believe azhrei has the right of it, it's not so much that the onload isn't triggering, it's that there's a syntax problem with your onload call.
But this code can also be improved in terms of better style (more readable/ easier to comprehend) by removing the second JS call.
In the header if you write:
window.onload = function() {
//everything inside your load() function goes here
}
It works just as well. It also removes a lot of the fluff that was just kind of there. I hope that helps.
Upvotes: 1
Reputation: 2323
You are supposed to supply a string to getElementById ...
So that:
document.getElementById(newsLeft).appendChild(divTag0);
Should be:
document.getElementById("newsLeft").appendChild(divTag0);
But the main problem is:
window.onload="load()";
Which should be:
window.onload=load;
Thanks to jvillars for the fiddle, which helped me notice this.
Upvotes: 4