Search code examples
javascriptinnerhtml

Change `innerHTML` of element using JavaScript


OK, I'm new at JavaScript, but I'm trying to change the innerHTML of a div element. Here is my script that is 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 it does not, any help?


Solution

  • 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.