Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript innerHTML not updating element

Tags:

javascript

Here is a very simple program and the output should be JavaScript but I am only getting s.

<html>     <head>         <title></title>         <script type="text/javascript">           document.getElementById("ma").innerHTML="JavaScript";         </script>     </head>     <body>         <h1 id="ma">s</h1>     </body> </html> 
like image 860
NullPoiиteя Avatar asked May 31 '12 02:05

NullPoiиteя


People also ask

Why does my innerHTML not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

How do I change the innerHTML of an element?

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.

Does innerHTML overwrite?

Yes, setting the . innerHTML properties overwrites any previous value for that property.

Does innerHTML reload pages?

When changing a html element with a function using innerHTML, the html element changes, but immediately the page reloads and the element is set back to his original value.


1 Answers

The element doesn't exist at the time you're attempting to set a value. You need to call this after the <h1> has been added to the DOM.

You can either move this <script> tag down further, or add your logic to a function which ought to be called when the document has been loaded:

window.onload = function() {     /* Add your logic here */ } 

Demo: http://jsfiddle.net/Lr2Hm/

like image 126
Sampson Avatar answered Sep 30 '22 16:09

Sampson