-5

HTML:

<p id="demo"></p>

the script:

document.getElementById("demo").innerHTML = 5 + 6;

It is supposed to show the result but nothing happens. I added a separate myScript.js file to write the code. In HTML I wrote:

<script type="text/javascript" src="myScript.js"></script>

What has to be the problem ?

Phil
  • 128,310
  • 20
  • 201
  • 202

1 Answers1

0

You need an element with id demo for this to work

document.getElementById("demo").innerHTML = 5 + 6;
<div id="demo"></div>

The problem in your case is probably the positioning of the included script tag. It is executed, as soon as it is parsed by the browser, but the demo tag is not loaded at this point.

Try

window.onload = function() {
    document.getElementById("demo").innerHTML = 5 + 6;
}

This will execute your code only after the document has loaded and the demo element is available.

MofX
  • 1,515
  • 12
  • 18
  • 1
    This was just a matter of format, the OP has added an element with this ID – GalAbra Aug 06 '19 at 06:59
  • I see. I will still leave the answer, because it shows that the exact code of the OP is working – MofX Aug 06 '19 at 07:00
  • 1
    _"Works for me"_ answers that have the same code as the question are not particularly helpful. The difference here that won't be obvious to OP is that the script part in Stack Snippets runs after the HTML is loaded – Phil Aug 06 '19 at 07:01
  • At the time I wrote it, it was not a "works-for-me" answer. – MofX Aug 06 '19 at 07:03
  • 1
    I refer to your comment ~ _"I will still leave the answer, because it shows that the exact code of the OP is working"_. Anyway, nice edit +1 – Phil Aug 06 '19 at 07:05
  • You are right. It was the heat of the moment ;) – MofX Aug 06 '19 at 07:05