Error Occured in document.getElementById('paintBox');

when i was writting

let paintbox = document.getElementById('paintBox');
console.log(paintbox);

in the vs code it gives me null
but when i paste the same lines in console directly , then canvas is accesed

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game1</title>
    <script src="Logic.js"></script>

</head>
<body>
    <h1>Canvas Game1</h1>    
    <canvas id='paintBox' height="500" width="500" style="border: 1px solid #000000"></canvas>
</body>
</html>


Javascript
let paintbox = document.getElementById('paintBox');
console.log(paintbox);

i checked logic.js is connected to html

what is the error here unable to find
plz help
thanks

github link of code

@anandprakash1091971 in vs code it gives you null, because there you are running the js file as a stand alone script, but in your browser, js is accessed through the html i.e. first your html page is loaded and then js operates on that page, that’s how canvas is accessed when in browser but not in vs code.

No
I was writing code in VS code but running it in browser
In browser console it is printing null
But when I write directly in console then it gives me Canvas
How to fix it
Because of this I am not able to apply other methods on it

@anandprakash1091971 then the problem might be that, your script is trying to call the method before the html page have even loaded completely. Try using this https://learn.jquery.com/using-jquery-core/document-ready/
what it will do is, it first waits for your document elements to be loaded and rendered and then execute the script

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

It may be TypeError: document.getelementbyid(…) is null - would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element. The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.