Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript change innerhtml

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?

like image 971
David Avatar asked Feb 12 '10 20:02

David


People also ask

How do I change content of innerHTML?

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.

How JavaScript can change HTML attributes?

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.

Can JS change the content of HTML elements?

JavaScript Can Change Content of HTML page: The getElementById() method is used to get the id of element and change the HTML content.


2 Answers

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.

like image 97
Aistina Avatar answered Oct 14 '22 09:10

Aistina


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()

like image 35
Anatoliy Avatar answered Oct 14 '22 10:10

Anatoliy