javascript change innerhtml

David picture David · Feb 12, 2010 · Viewed 49.5k times · Source

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?

Answer

Aistina picture Aistina · Feb 12, 2010

Rather than assigning var1 to window.onload, you're currently calling the function and storing its result. Also, this might be obvious, 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.