Skip to content
Advertisement

JavaScript innerHTML not updating element

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>

Advertisement

Answer

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/

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement