Search code examples
javascripthtmlinnerhtml

When using document.getElementById, it's not working properly


The Problem
I'm trying to display the output of a function to a div, but i can't figure out why it isn't displaying. How can i fix this so that it displays properly?

What i've tried so far
I've copied a document.getElementById statement from another codeblock i wrote that is functioning , and checked it for any typos etc. All seems well there. I googled innerHTML to be sure that I was using it correctly.
Also changed the document.etc line to document.write to ensure the function was working properly, it output properly.


My Code

<html>
<head>    
<script type="text/javascript">
    function parameters(one, two) {
        document.getElementById('output').innerHTML=(one + two);
    }

    parameters("coding" , "coffee");
</script>
</head>    
<body>
    <div id="output"></div>
</body>
</html>

Solution

  • The problem is that you're trying to use the div#output before it's even loaded by the browser.

    There are two simple solutions for this:

    First

    Put the <script> tag after the div#output, so it will be already loaded.

    <html>
    <head>
    </head>
    <body>
      <div id="output"></div>
      <script type="text/javascript">
        function parameters(one, two) {
          document.getElementById('output').innerHTML=(one + two);
        }
    
        parameters("coding" , "coffee");
      </script>
    </body>
    </html>
    

    Second

    Put your Javascript code inside the DOMContentLoaded event, so it will only be called after all the DOMElements are loaded in your page.

    <html>
    <head>
      <script type="text/javascript">
        function parameters(one, two) {
          document.getElementById('output').innerHTML=(one + two);
        }
    
        document.addEventListener('DOMContentLoaded', function() {
          parameters("coding" , "coffee");
        });
      </script>
    </head>
    <body>
      <div id="output"></div>
    </body>
    </html>