document.getElementById() not working

Hello, I tried to use event listener on an element but document.getElementById() returns null instead of the element. The problem is that I can't find any problem and I tired the code on multiple online compiler and it worked in all of them but it doesn't work on VScode. HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<button id="test">test</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<button id="test">test</button>
</body>
</html>
JavaScript:
let test = document.getElementById("test");
console.log(test);

test.addEventListener("click", () => {
console.log("test passed");
});
let test = document.getElementById("test");
console.log(test);

test.addEventListener("click", () => {
console.log("test passed");
});
5 Replies
Mannix
Mannix•2y ago
if you load script file in the head add defer attribute on it 😉
Wolle
Wolle•2y ago
Your <script> gets run the moment it gets loaded, that is probably before the HTML is fully parsed. To counter this, you can add defer to your <script>, so it gets loaded after the HTML is rendered.
8
8OP•2y ago
The funny part is that I just learned this yesterday I am so dumb
Wolle
Wolle•2y ago
Naw, some things just take a few times doing them wrong till they stick 😉 just keep at it
8
8OP•2y ago
Thank you very much!
Want results from more Discord servers?
Add your server