-2

I completely revised this question with the below code to show the sample error I'm receiving.

Javascript.js file

var yourName = prompt("What is your name?");
if (yourName != null){
document.getElementById("sayHello").innerHTML = "Hello" + yourName;}
else {
alert("Please enter a name next time!");}

index.html

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="Javascript.js"></script>
</head>

<body>
<p id="sayHello">hello</p>
</body>
</html>

The above code will prompt me the message to ask for the name which it will receive, but with the 'yourName' variable, the document.getElement line won't run because the html code

remains the same as 'hello'. I tried to debug this to see why it won't run through the document line code but I get a message when I click to breakpoint on the document line, 'The breakpoint will not currently be hit. No symbols have been loaded for this document.' What symbols is it referring to? I am using Microsoft Visual Studio.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Zulu
  • 81
  • 2
  • 9
  • 2
    You'll have to provide more information, notably your **javascript** (js) file. Simply pasting a screenshot of the HTML isn't enough for us to know what is happening. – romellem Jul 19 '17 at 21:45
  • Is it possible that you misclicked somewhere on your dev tools an created a breakpoint? – krankuba Jul 19 '17 at 21:48
  • You know what, I just discovered that if I code the javascript internally like this image: http://imgur.com/a/NOEfH It ends up working! So.. why is that? – Zulu Jul 19 '17 at 21:49
  • Here is the whole JS file: http://imgur.com/a/TUZDj – Zulu Jul 19 '17 at 21:53
  • Please paste the actual code into your question. – 9999years Jul 19 '17 at 21:56
  • @9999years I just revised and edited the question again – Zulu Jul 28 '17 at 01:57

1 Answers1

1

In answer to your question of why it works when placed late in the html (in the comments):

The script needs to run when the DOM has been set up so that it can find the element.

Currently the script is running BEFORE the html is accessible, so getElementById won't be able to find anything.

Simplest correction is to place the script at the end of the <body> tag (after the html it references; as you did in your screenshot).

Another other option is to have the script run only when the DOM has finished loading: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

K Scandrett
  • 15,287
  • 4
  • 33
  • 59