NotKnock
NotKnock

Reputation: 39

Why does this code not work? Javascript and HTML. Please see the details

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.

Upvotes: 1

Views: 61

Answers (2)

Gopinath
Gopinath

Reputation: 4957

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

Upvotes: 0

Quentin
Quentin

Reputation: 944530

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>

Upvotes: 4

Related Questions