0

I am creating a very simple HTML file and I am trying to link it to a JavaScript file so that the text changes when I click on it.

I have copied it almost entirely from W3 and it works when I place the javascript code within the HTML script tags, but when I try to source it using the script tags (see the first example below) I am not able to get the JavaScript file to link to the HTML.

Any help you can give me is appreciated. I am currently using Visual Studio Code to do this if that gives any hints as to what I am doing wrong.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TextChange</title>
    <script src="js/script.js"></script>
</head>
<body>
    <p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
    <p id="demo">Click me.</p>
</body>
</html>

JavaScript

document.getElementById("demo").onclick = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}

Alternate HTML that works

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TextChange</title>
</head>
<body>
    <p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>
    <p id="demo">Click me.</p>
    <script>

document.getElementById("demo").onclick = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}

    </script>
</body>
</html>

When I render the HTML and view the source and click on the .js extension, I am able to view the javascript file. Despite this, the text that I want to change when I click on it does not change if I click on it.

2 Answers2

0

Your JS file is included before the element, so getElementById() returns null.

Move it after the element, or make it wait for the document's loaded event.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Your script tag must be on the bottom of your html code (before the closure of <body> tag) so your javascript can use and detect the different DOM elements after they get rendered :

<html>
  <body>

  <!-- your code here -->

   <script src="js/script.js"></script>
  </body>
</html>
Abdelillah Aissani
  • 3,058
  • 2
  • 10
  • 25