When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with:

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

While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript:

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

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

The function Open_Populationdiv() is defined by me. Although all seems to be set up correctly, I keep receiving an error message in the console and the script fails to execute:

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

Answer №1

One reason for the error occurring is that the function is being executed before the Document Object Model (DOM) is fully loaded, resulting in the div element being null when the event listener is added.

To prevent this issue, you can include a conditional statement to check if the div element exists before proceeding with adding the event listener:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Having trouble loading Yeoman Webapp SASS

Every time I try to build a web application using 'yo webapp', I encounter a 404 Error. GET http://localhost:9000/styles/main.css 404 (Not Found) I removed compass from the project, but that shouldn't be causing the issue, correct? ...

Running a Node.js child process upon clicking an HTML button

I need to create a basic webpage where clicking a button will open the command prompt. This is my goal. Below are the HTML and Node.js code snippets. test.html <html> <head> </head> <body> <p>guru</p> <form a ...

dividing Handlebars HTML content into different files or sections

I am looking to design a single route webpage, but I would like to divide the HTML code into multiple files. When rendering this particular route, my goal is for the rendered file to pull content from different template files and combine them into one coh ...

Codeigniter code to retrieve dynamic data in a select box

I am trying to implement a functionality where selecting an option from one dropdown will dynamically populate the options in another dropdown based on the selection. I believe I need to use an onchange function, but I'm unsure how to retrieve data fr ...

How to pass arguments to a function within a preg_replace in PHP

Greetings! I currently have a situation similar to this: $content = preg_replace('#(\s*)\<pre(.*?)\>(.*?)\</pre\>(\s*)#sie', 'dostuff(\'\\3\', \'\\2 ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

Click to switch divs

I am struggling and in need of help. I have been trying to rotate divs on click using jQuery, which was successful until I had two sets of divs that needed to be rotated independently on the same page. When clicking on the arrows to rotate the content in t ...

Error: Query has already been processed: Updating Todo with ID "612df063a8f"

After updating mongoose to the latest version (6.0.2), I encountered an error that crashes the application whenever .updateOne() is executed. However, the object is still updated inside the database. Below is my code snippet: async(req,res) => { a ...

Retrieving text content from an HTML element with Jsoup for web page manipulation

My task involves extracting text content from a specific HTML element <span class="adr" style="float: none !important;"> <span class="street-address" style="float: none !important;">18, Jawaharlal Nehru Road, </span> ...

How can Watir retrieve the inner html content of a <span> element?

Currently, I am attempting to locate a navigation link by iterating through several spans with the 'menu-item-text' class. My objective is to compare the content within the span tags to determine if it matches the correct navigation control for c ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

Spacing between table cells is only applied to the first row and footer

In an attempt to add spacing between the first row, second row, and footer of a table, I have experimented with cell spacing combined with border-collapse. However, the spacing is being applied all over the table instead of in specific areas. I am utilizin ...

Enhancing a Bootstrap 4 navbar menu system with padding tweaks

Just starting out with Bootstrap 4 and creating a practice page with a header to familiarize myself with the navbar system. I have put together this jsFiddle (full code) for reference, but essentially, my page structure is as follows: index.html <nav ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

What is the best way to connect information from an HTML input field to a JavaScript object with the help of AngularJS?

As a beginner in AngularJS, I'm struggling to find the best approach to achieve my goal. I aim to create a grid of input tags with type=number in my HTML and have it set up so that whenever the value is increased, a new object is added to a list. Simi ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

How can I dynamically generate multiple Reactive Forms from an array of names using ngFor in Angular?

I am in the process of developing an ID lookup form using Angular. My goal is to generate multiple formGroups within the same HTML file based on an array of values I have, all while keeping my code DRY (Don't Repeat Yourself). Each formGroup will be l ...

Is there a way to compare the elements of an array with those of another array containing nested arrays in order to identify matching results?

Every user in our database has specific skills assigned to them. We maintain a list of available skills with unique IDs. The objective is to filter users based on the skill we are interested in, like displaying all Janitors. We are utilizing Vue.js and im ...