-1

I can't succeed in calling JavaScript file from a HTML file.

test.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script  src='http://code.jquery.com/jquery-3.2.1.min.js'</script> 
    <script type='text/javascript' src='test.js' </script>
    <script>theTest(); </script>
</head>
<body>
    <div id="myTest" style="position:relative;width:600px;height:400px;"></div>
</body>
</html>

test.js:

function theTest()
{
    var they = 2;
    console.log(they);
    alert(they);
};

document.getElementById('myTest').innerHTML;

I am receiving:

ReferenceError: document is not defined

9
  • Take a look at this answer. Commented Sep 11, 2017 at 13:44
  • @julekgwa:Sorry, what do you mean a typo? Commented Sep 11, 2017 at 13:47
  • 1
    Is the missing > in your jQuery <script> tag a typo here, or in your original code? Commented Sep 11, 2017 at 13:48
  • 1
    ^ Better yet, of the three <script> tags, only one is properly closed. Commented Sep 11, 2017 at 13:49
  • 1
    @freginold Both the jQuery and the test.js. Commented Sep 11, 2017 at 13:49

1 Answer 1

0

You are calling theTest(); before the browser is generating the #myTest element, or even starting to build the page, so the function has nothing to act on. Move your third script tag down to the end of your body element, and it should work fine. See this example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src='http://code.jquery.com/jquery-3.2.1.min.js'></script> 
    <script type='text/javascript' src='test.js'></script>
</head>
<body>
    <div id="myTest" style="position:relative;width:600px;height:400px;"></div>
    <script>
        theTest();
    </script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

14 Comments

H, thanks but I am still getting the error about document not found.Let me remind you that I want to call the javascript file which executes the html file and not the opposite.
But the function is not calling any page element.
@George Where are you loading the HTML file from your JavaScript file?
@George That line of code does literally nothing. You're getting the HTML content of the myTest element, but you're not saving it, changing it, doing anything with it, etc. For example, document.getElementById('myTest').innerHTML = "Hello world!" would set the HTML. var myHtml = document.getElementById('myTest').innerHTML; would store it as a variable. But that line on it's own has no purpose.
@freginold:node test.js
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.