views:

347

answers:

6

ok im new at javascript, but im trying to change the innerhtml of a div tag, heres my script and its not working:

<head>
<script type="text/javascript">
function var1() {
document.getElementById('test').innerHTML = 'hi';
}
window.onLoad = var1();
</script>
</head>
<body>
<div id="test">change</div>
</body>

it should work but for some reason its not, any help?

+1  A: 

You're getting an element with an id of "test", but there is no element with that id in your html. There is, however, one called "text".

Tim S. Van Haren
oh sorry, i fixed that i didnt copy and paste from my text just typed it in here, my bad. but yeh still doesnt work
David
+3  A: 

correct:

window.onload = var1;

in your example value of window.onload is undefined because function var1 returns nothing (undefined). You should set onload property to function var1, not result of calling function var1()

Anatoliy
still doesnt work..
David
@David: Notice also the change from onLoad to onload. I tried it and it works just fine.
Guffa
+5  A: 

Rather than assigning var1 to window.onload, your currently calling the function and storing its result. Also, this might be obvious to point out, but var1 seems like an odd name for a function. Try this:

function var1() {
  document.getElementById('text').innerHTML = 'hi';
}

window.onload = var1;

Note the casing of onload, as well as the missing parentheses after var1.

Aistina
you should not use innerHTML it is non-standard and a bad practice. It’s a lot safer to use DOM methods like createElement, createTextNode and appendChild.
fuzzy lollipop
A: 

Try changing onLoad to onload.

function var1() {
document.getElementById('test').innerHTML = 'hi';
}
window.onload = var1(); // onload
johnmdonahue
It’s a lot safer to use DOM methods like createElement, createTextNode and appendChild.
fuzzy lollipop
A: 

using .innerHTML is considered bad practice, it is non-standard, you should create a new element and add it to the tree instead

fuzzy lollipop
No. Using `innerHTML` is the fastest way.
Josh Stodola
doesn't mean is isn't bad practice
fuzzy lollipop
It's non standard, therefore it can lead to undefined behaviour, ie: security flaws, thus is bad practice. I can't believe someone voted this down...
Longpoke
A: 

Your example will work if you change the uppercase "L" to a lowercase "L" in "onLoad" and remove the parenthesis after var1 where you currently have window.onLoad = var1();

pdavis