-1

How do i make this code work with an external javascript file?

<!DOCTYPE html>
<html>
<body>

<h2>My First Page</h2>

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

<script>
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
</script>

</body>
</html>

If i try to write this inside script.js file it will return this error: "TypeError: elem is null"

OBS: I have no problems running this as inner HTML, just the external part is getting me.

Black US
  • 9
  • 3
  • load your script file right before `

    ` tag

    – Muhammad Usman May 18 '18 at 20:57
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – JJJ May 18 '18 at 20:59
  • Possible duplicate of [$(document).ready equivalent without jQuery](https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Kevin Boucher May 18 '18 at 21:01
  • What is "OBS"? All Google tells me is Open Broadcaster Software. –  May 18 '18 at 21:01
  • Next time when you ask a question, post the version that *doesn't* work, not the one that works. In this case it's easy to guess what the problem probably is but that's not always the case and without seeing the non-working version you can never know for sure. – JJJ May 18 '18 at 21:02
  • @Amy - Observation – Black US May 18 '18 at 21:21

3 Answers3

1

If your script is run before the DOM has finished loading (and specifically the #demo element is not yet present), your call to getElementById will return null.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

So, you need to ensure that the DOM has been loaded before querying for that element.

You can either place your script tag at the end of the document (as suggested elsewhere in this post), or utilize the DOMContentLoaded event:

window.addEventListener('DOMContentLoaded', function() {
    var elem = document.getElementById("demo");
    elem.innerHTML = "Hello World!";
});
Kevin Boucher
  • 14,990
  • 3
  • 40
  • 54
0

Embed your javascript file before closing the body tag, so that your javascript file runs after the page loads. Otherwise your code will run before the demo element added to the page:

<script src="external.js"></script>

And use only inner part of the inline script in the external file:

var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
snnsnn
  • 3,072
  • 21
  • 22
0

Import your external javascript file at the end of the DOM. When you call your javascript file at the header, your script searches element before being loaded. That's why it gives error. Try this now!

<!DOCTYPE html>
<html>
    <body>

        <h2>My First Page</h2>

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

        <script src="script.js"></script>
    </body>
</html>
Masood
  • 1,031
  • 12
  • 24