document.querySelector(...) is null error

file.js

const heading1 = document.querySelector(".heading1");
console.log(heading1);

Solution 1


Use defer (best & recommended way):

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="./file.js" defer></script>
    <title>Document</title>
</head>
<body>
    <h1 class="heading1">Hello World 1</h1>
</body>
</html>

Solution 2

Place your JavaScript in bottom before closing body tag

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h1 class="heading1">Hello World 1</h1>

    <script src="./file.js"></script>
</body>
</html>

document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.

I would suggest you call all JS script bottom of the page.


To make sure that your DOM is ready you could add this to your JS file.

// my-script.js
document.addEventListener("DOMContentLoaded", function() { 
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.querySelector('input[type=file]')
        .addEventListener('change', function(event){
            ...
         }
});

This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.

Also take a look at this other Google rule.