-5

Allow me to restate my problem. These are the givens:

main.html

<html>

<head>

 `<script type="text/javascript" src="js/MyJS.js"></script>;`

</head>

<body>

<script>

document.getElementById("DisplayVar").innerHTML = a;

</script>

<div id="DisplayVar">

</div>

</body>

<html>

MyJs.js

var a = 1;

Nothing is displayed in the "DisplayVar" div, and the developer console says that (a) is undefined. Why is this?

b1az3
  • 1
  • 1

1 Answers1

0

You have to assign innerHTML of the "DisplayVar" div after creating it

<head>
  <script type="text/javascript">
    // or source to MyJS.js
    var a = 1;
  </script>
</head>
<body>
  <div id="DisplayVar"></div>
  <script>
    if(document.getElementById("DisplayVar"))
      document.getElementById("DisplayVar").innerHTML = a;
  </script>  
</body>

See codepen, I added a reference to an external js file, and used one of the variables defined there.

I also changed the position of the inline script. It should be placed after the creation of destination div element.

Daniel Faure
  • 312
  • 3
  • 11
  • yes but the point of my question is that the variable (a) is in a separate file and that's why it isn't working. If i define (a) in `main.html` than it works just fine. I need it to work between files. – b1az3 May 14 '18 at 23:06
  • the second script cannot assign innerHTML to an element that still does not exist – Daniel Faure May 14 '18 at 23:17