0

I have html like this

<button class="pop-btn">
  Pop 
</button>        

I was able to style it with css but I can't select it in my Javascript:

const Population_div_Button=document.querySelector(".pop-btn");

Population_div_Button.addEventListener("click", function(){
    Open_Populationdiv();
});

where Open_Populationdiv() is a function I wrote. Everything seems to be in place but I still get an error message on console, and the script doesn't work:

Uncaught TypeError: Population_div_Button is null http://127.0.0.1:5500/app.js:6

Lawrence Cherone
  • 41,907
  • 7
  • 51
  • 92
Vni Versvs
  • 11
  • 2
  • Your class is `pop-div` but in your querySelector you use `pop_div` – lbragile Dec 22 '20 at 23:12
  • those comments are correct for div, but i think the problem lies with with the button – Vni Versvs Dec 22 '20 at 23:18
  • guys, the button has a class attribute, not an id attribute – Vni Versvs Dec 22 '20 at 23:20
  • Ignoring the previous mentioned problem with the div, I tested your code and it works. Which means, I'm wondering if the problem is with the placement of the javascript itself. Are you placing the javascript in the head or bottom of the website? If you are placing it in the head, you will want to wrap it in `window.addEventListener('DOMContentLoaded', (event) => {` since it is referencing dom elements that don't exist yet. – imvain2 Dec 22 '20 at 23:21
  • oh my, is there such a thing as where i place the javacript? – Vni Versvs Dec 22 '20 at 23:31
  • @VniVersvs, depending on what the javascript is doing, the placement is important. For example, when you are referencing an element on the screen (like a button) the javascript will need to be either delayed from running or loaded below the button (ie at the very bottom of the body. The reason for this is the javascript is being parsed before the elements are processed so the javascript doesn't know those elements exist if it is ran at the top. – imvain2 Dec 23 '20 at 16:28

1 Answers1

-2

That error happens because the function is running before the DOM is ready, so that div element is null when you are adding the event listener.

You might want to add a condition before executing that line:

if(Population_div_Button !== null){
   Population_div_Button.addEventListener("click", function(){
       Open_Populationdiv();
   });
}
jfrayo
  • 1
  • 4