3

This is my HTML file.

   <body>
            <header>
                <h3 id = "TestID"> Test </h3>
            </header>
        </body>

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

This is my JS file

document.getElementById("TestID").addEventListener("load", function(){
this.innerHTML("Hi");
})

document.write("Hello World");

Now, when I load the HTML, I get "Test" in the browser. However, what needs to be there is "Hi". I do not understand why this happens. Can you please help me understand? I am just getting started, so please explain in simple terms.

Thanks for taking the time to read through this :)

NotKnock
  • 43
  • 3

2 Answers2

4

You have two problems.


Only elements which load external content have a load event (such as an iframe or img).

The h3 isn't loading any external content so has no load event.

Perhaps you should bind your event handler to the window.


innerHTML is a string, not a function.


addEventListener("load", function() {
  document.getElementById("TestID").innerHTML = "Hi";
})

document.write("Hello World");
  <header>
    <h3 id="TestID"> Test </h3>
  </header>

<script src="MessagingPage.js"></script>
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 1
    This is true. But it's worth noting a couple of things. You can call `addEventListener` wihtou adding a variable at the beginning because every global object in a browser is interpreted as if it was used on the `window` object. So `addEventListener` is the same as `window.addEventListener`. And placing a `script` tag outside of the `body` is not valid html. It will work in most browser though, but the html spec forbids it – Mark E May 03 '20 at 21:46
0

Including the script inside <body> and updating the JS file will resolve the problem.

Here is the example of working code:

Updated HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Demo</title>
  </head>
  <body>
    <header>
      <h3 id = "TestID"> Test </h3>
    </header>
    <script src = "/MessagingPage.js"></script>
  </body>
</html>

Updated JS:

// MessagingPage.js
document.getElementById("TestID").innerHTML = "Hi"
document.write("Hello World");

Output:

enter image description here

Gopinath
  • 3,185
  • 1
  • 8
  • 14