Confused about VSC and Live Server to do JS tutorial

  1. I have Windows 11.
  2. I’m new to learning JS and running Live Server.
  3. I’m running Visual Studio Code v1.119 and the Live Server extension.
  4. I have made my HTML file and script.js file and the HTML file references the script.js file like this: <script src="./script.js"></script> They are in the same directory.

When I clicked Go Live at the bottom of the VSC window a Chrome browser window opened up, and it displays my web page. Here’s my Javascript:

console.log("Hello");
//Get element by id
let hdr = document.getElementById('myheader');
console.log(hdr); 
hdr.style.color = "red";

The console displays “Hello” just fine. But when I display “hdr” it is null. It is like “document” does not exist at all.

In this line hdr.style.color = "red"; I get an error in the Chrome console: “script.js:6 Uncaught TypeError: Cannot read properties of null (reading ‘style’)”.

The next error in the Chrome console below that is: “Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received”.

I must be doing something wrong but I’m not sure what. Can someone help please?

Thank you.

EDIT: The JS tutorial I’m doing is from Freecodecamp and is here: https://www.youtube.com/watch?v=c6IyCwAV6BY. It is from October 2025 so it’s not that old. The styling portion begins at 26:14.

PROBLEM: I’m trying to get and set the styles for elements already in the HTML file and none of that works due to this error.

Here’s my HTML.

<!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">
  <title>Test Document 5/11/26</title>
</head>
<body bgcolor="#c0c0c0">
  <script src="./script.js"></script>
  <h1 class="title" id="myheader">This is header.</h1>
  <p id="1">This has id=1.</p>
  <p id="2" class="class1"><span style="background:lime;">This is a span. This has id=2 and class="class1".</span></p>
  <div class="form-group">
    <label>Amount</label>
    <input type="text" placeholder="$0.00" id="amount" name="amount"/>
  </div>
  <div class="form-group">
    <label>Date</label>
    <input type="date" id="mydate" name="mydate" />
    </div>
  <! img src="https://cdn.pixabay.com/photo/2024/02/28/07/42/european-shorthair-8601492_1280.jpg" width="200" />
</body>
</html>

This same HTML and Javascript works fine on jsfiddle dot net but jsfiddle does not display objects in the console the same way as the tutorial.

Hi @croberts,

Please move this line of code to just before the closing body tag so your JavaScript is loaded after the DOM.

Happy coding!

OMG, that worked. I had no idea. Thank you!