0

I've below HTML code -

<!DOCTYPE html>
<head>
    <title>Intro to Js</title>
    <link rel="stylesheet" type="text/css" href="css/style.css"> </link>
    <script type="text/Javascript" src="scripts/index.js"></script>
</head>
<body>
    
    <h1>Introduction to Javascript</h1>
    <hr/>
    <div id="ResultContainer"></div>
    
</body>
</html>

below javascript scripts/index.js

var resultContainer = document.getElementById("ResultContainer");
resultContainer.innerHTML = "Setting up environment";

below is the css/style.css

body {
    margin-top: 20px;
    margin-left: 20px;
}

h1 {
    font-size: 50px;
}

#ResultContainer {
    font-size: 30px;
    margin-top: 30px;
    padding: 10px;
    width: 450 px;
    height: 200px;
    border: 1px solid black;
}

when I run the code using start command I get error

Uncaught TypeError: resultContainer is null http://localhost:3000/scripts/index.js:6

enter image description here

But the same code in codepen is running fine.

Any idea how can I fix the error in local?

user51
  • 8,843
  • 21
  • 79
  • 158
  • Maybe Codepen moves some logic only when DOM is ready? You did not specify at which lifecycle point you are creating resultContainer – pierpy Jul 13 '23 at 05:23

2 Answers2

2

Your code is running before the DOM is fully loaded (element does not exists).

To solve the issue you can either place the script at the bottom of the body tag or wrap your code with DOMContentLoaded which will ensure that your code executes only after the page is fully loaded:

window.addEventListener("DOMContentLoaded", (event) => {
  var resultContainer = document.getElementById("ResultContainer");
  resultContainer.innerHTML = "Setting up environment";
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

the script tag doesn't go in the header as it won't be able to read the boyd elements, put it in the body tag

<!DOCTYPE html>
<head>
    <title>Intro to Js</title>
    <link rel="stylesheet" type="text/css" href="css/style.css"> </link>
</head>
<body>
    
    <h1>Introduction to Javascript</h1>
    <hr/>
    <div id="ResultContainer"></div>
    <script type="text/Javascript" src="scripts/index.js"></script>
</body>
</html>