0

When I am tryin to get my elements from my html file using document.getElementById, I get null for all three const variables

The following is the beginning of my js file :

    const postBtn1 = document.getElementById("post-btn1");
    const postBtn2 = document.getElementById("post-btn2");
    const postBtn3 = document.getElementById("post-btn3");

The following is the beginning of my html file and section containing the buttons:

<link rel="stylesheet" href="css/animate.css" />
<link rel="stylesheet" href="css/icomoon.css" />
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/superfish.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="js/money-request.js"></script> <!-- this is the js file I'm using for this part -->
<script src="js/modernizr-2.6.2.min.js"></script>
</head>
  • 1
    Some things I have found over my time as a programmer. ` – RingGamesCompany May 01 '20 at 02:02
  • Does this answer your question? [Why is getElementById returning null](https://stackoverflow.com/questions/61442589/why-is-getelementbyid-returning-null) – Nilanka Manoj May 01 '20 at 02:14

1 Answers1

0

The JS file is executed right away after it is loaded (Before the HTML buttons are rendered.)

Make sure you wrap your button access code inside an onload block:

window.onload = function() {
  const postBtn1 = document.getElementById("post-btn1");
  const postBtn2 = document.getElementById("post-btn2");
  const postBtn3 = document.getElementById("post-btn3");

  console.log(postBtn1);
};

This ensures the code inside the function block is only executed after the html page is fully rendered and they won't be null anymore.

To learn more about this, check out https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

Codier
  • 2,126
  • 3
  • 22
  • 33
  • I would use `addEventListener('load', ()=>{ /* code here */});` for `window.onload`s, since you would have to store the prior `onload` in a variable, then call it again within the `onload` to use it more than once. Using `load` more than once is a common practice. Otherwise, *(besides window.onload)* I prefer assignment style eventListeners myself. And... yes, you can leave `window.` off. It's implicit. – StackSlave May 01 '20 at 02:12