document.getElementById(); returns null on an id that definitely exists

3.1k views Asked by At

Does anyone know why document.getElementById("closebtn"); returns null? I have tried console.logging it, and i just get null. I am using node.js and Electron

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="home.css" />
    <script>
    console.log(document.getElementById("closebtn"));</script>
</head>
<body>
    <div id="menubar">
        <button id="closebtn" onclick=""></button>
    </div>
</body>
</html>
1

There are 1 answers

0
Mamun On BEST ANSWER

This is because your script is running before the DOM is fully loaded. You can either place the script at the bottom of the body or wrap your code with DOMContentLoaded. This will ensure that code placed inside will only be executed once the DOM is fully loaded.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="home.css" />
    <script>
    document.addEventListener("DOMContentLoaded", function(event) {
      console.log(document.getElementById("closebtn"));
    });
    </script>
</head>
<body>
    <div id="menubar">
        <button id="closebtn" onclick=""></button>
    </div>
</body>
</html>