0

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>
Buzinas
  • 11,597
  • 2
  • 36
  • 58
NewCoder101
  • 31
  • 1
  • 5

1 Answers1

2

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>
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • Okay, thank you very much, that clarifies things. Lesson learnt, can't run what's not loaded yet. – NewCoder101 Sep 22 '15 at 16:59
  • @NewCoder101 if my answer was useful for you, please click on the arrow to upvote it, and on the `V` to mark it as accepted! – Buzinas Sep 22 '15 at 17:00
  • Upvoted, and can't accept for another four minutes, but i appreciate everyones time, thanks for clearing it up, i would never have thought about it not actually being loaded yet. – NewCoder101 Sep 22 '15 at 17:02