0

Can someone explain me how to use document method in external .js file for Visual Studio Code?

What i do: I have an index.html file:

<!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>Document</title>
</head>
<body>
    <table>
        <tbody id="tbody"></tbody>
    </table>
    <script src="script.js"></script>
</body>
</html>

And script.js file:

var tbody =  document.getElementById("tbody");

For running I select script.js file and start debugging (fn+F5) I get ReferenceError: document is not defined, see screenshot: http://prntscr.com/kfp60b

I understand that my browser is not opened and DOM is not exised yet, but how can I debug this method in external js file? how to run properly?

2 Answers 2

0

Try

var tbody =  window.document.getElementById("tbody");

Also, see this about including the type tag when declaring your script:

Which is better: <script type="text/javascript">...</script> or <script>...</script>

You should see something like this when you debug with chrome: enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Tried with window - I get "ReferenceError: window is not defined"
Are you launching your index.html file by double clicking on it and selecting "Chrome" as your browser? it sounds like you're trying to launch the javascript file directly however if you do that it doesn't have an association back to your index.html file.
When in Chrome you hit F12 to bring up the debugger (Windows).
Yes, I tried this case also: 1. Open my index.html in chrome browser 2. run debug in script.js file and get the same error. I google and see that I need to add some task file to each folder to specify some configurations . Maybe it's help me?
0

I found that I have to use some plugins for run browser, for example Debugger for Chrome If you want invoke browser when I start debugging .js file - you need to install this plugin to vs code and create launch.json file with configurations:

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch index.html",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceFolder}/sample/index.html"
        },
    ]
}

In debugging time -vs code will show you message launch index.html - and after confirmation chrome browser opens appropriate file.html.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.