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?
To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.
JavaScript Can Change Content of HTML page: The getElementById() method is used to get the id of element and change the HTML content.
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
.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With