-2

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>
Dextication
  • 715
  • 1
  • 8
  • 23
  • https://stackoverflow.com/questions/32780726/how-to-access-dom-elements-in-electron – robbannn Jan 18 '19 at 13:05
  • 1
    Move your script to just before `

    `. The DOM needs to load before you can access it with the code.

    – Andy Jan 18 '19 at 13:05
  • Your script is loaded before your DOM here. Put it at the end or call your method after the DOM is loaded – Alexis Jan 18 '19 at 13:06

1 Answers1

2

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>
Mamun
  • 58,653
  • 9
  • 33
  • 46