Home > Net >  why is document.getElementById() not working in VS Code?
why is document.getElementById() not working in VS Code?

Time:10-22

why is document.getElementById() not working in VS Code?? I keep getting this error: "Uncaught ReferenceError ReferenceError: document is not defined". I'm new to VS Code but I'm assuming the reason It's not working is that I need to install some extension to make it work. The same code is working on Replit but not VS code. I installed JS(ES6) Snippets, Open-in browser, Live Preview and Live Server. It's very simple 2-line code just to experiment but it's not working. It's driving me crazy!

let head = document.getElementById('change')
head.innerText = 'hello'

CodePudding user response:

I bet that you are not running this in an index.html file in the browser, so this is not VS Code problem, you are probably running this in a node console or something, there is no html or document in what you are trying to test and that is why you are getting this error.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<h1>HELLO</h1>
<hr />
<h2 id="change"></h2>
<script>
    let head = document.getElementById('change')
    head.innerText = "why isn't this working?";
</script>
</body>
</html>

CodePudding user response:

This not the vscode issue please check you are running the right file

CodePudding user response:

Definitely has nothing to do with VS Code.

Make sure your html file is referencing your javascript file.

    <!DOCTYPE html>
<html>
<body>

<h1>This is my HTML file</h1>

<script src="script.js"></script>

</body>
</html>

The script element should be in your html with the name of your js file

<script src="script.js"></script>
  • Related