skip to Main Content

I am learning about manipulating the DOM w/ javascript.

I understood that JS can only access the DOM in a browser-environment, because the DOM is only available in the browser, and JS, being a "client-side" language, can run on the browser, access the DOM, and manipulate it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World</h1>
    <script src="script.js" type="text/javascript"></script>
  </body>
</html>

const heading = document.querySelector("h1");

console.log(heading);

Every time I tried to access the ‘document’ object before, I got:

ReferenceError: document is not defined

I was using the "run" button on the visual studio code IDE., The given error was displayed on the IDE’s panel (output section). I didn’t open it on the browser. I know VSCode is not a browser-environment. What is another way I can configure my code, so it will be able to access the DOM?

I went inside my HTML document that I have used the "Live Server" extension to run (on VSCode), right-clicked to inspect, and the javascript code works alright inside the browser, because the DOM is accessible within the browser. It seems impractical to write code in the IDE and then go to the DevTools on the browser to check if everything is correct every 5 seconds. Is there any way to correlate my IDE, the webpage, and the DOM instead of inspecting the HTML document after every refresh?

2

Answers


  1. change your JavaScript like following:

    window.onload = function() {
        const heading = document.querySelector('h1');
        console.log(heading);
    }
    

    It seems like that your JavaScript file gets executed before your DOM has finished to load.

    Make sure that you copy your file path in the browser URL.

    Instead of: https://google.com/
    –> PATH TO FILE

    Login or Signup to reply.
  2. If you run your script inside your IDE (Visual Studio Code), there is no access to the DOM because it does not exist for your script. Your script will only work if it is executed within an HTML page. If you include your script in this way and open the HTML file in your browser, you can click ‘Inspect’ and navigate to the console. You will then see the heading printed out.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search