Unable to add an event while looping through a NodeList in JavaScript

Seeking assistance in iterating a NodeList object using javascript, and implementing a click event for each item :

document.addEventListener("DOMContentLoaded", async () => {
try {

    posts.map(post => {
        container.innerHTML += outPutHtml(post); // user-interaction elements are created with ajax request 
} catch (e) {
    console.error(e);
   
} finally {
    highlight.highlightAll();

});

const elements = document.querySelectorAll(".user-interaction");

console.log(elements); //   NodeList []length: 0[[Prototype]]: NodeList
console.log(typeof elements); // object

elements.forEach(function(element) {
    element.addEventListener("click", function() {
        console.log('ok');
    });
});

The click event on element doesn’t seem to work!

In need of a solution to fix this issue.

Answer №1

const addListeners = () => {
  const elements = document.querySelectorAll(".user-interaction");

  console.log(elements); //   NodeList []length: 0[[Prototype]]: NodeList
  console.log(typeof elements); // object

  elements.forEach(function(element) {
    element.addEventListener("click", function() {
      console.log('ok');
    });
  });
};

async function makeAjaxrequest() {
  return new Promise((resolve) => {
    setTimeout(resolve, 2000);
  })
}




const runTheApp = async() => {
  console.log('start')
  await makeAjaxrequest();
  console.log('done')
  addListeners();
}


runTheApp();
.user-interaction {
  cursor: pointer;
}
<div class="user-interaction">1</div>
<div class="user-interaction">2</div>
<div class="user-interaction">3</div>

rewrap your code within

window.addEventListener('DOMContentLoaded', (event) => {
   console.log('place your logic here')
});

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

Difficulty encountered with document.querySelectorAll retrieving paginated elements

I am currently developing a project called STEEP. Our implementation involves utilizing infinite scroll to load 8 videos at a time as the user scrolls through the page. However, we are facing an issue with the script responsible for handling video playbac ...

Ensuring accuracy within a personalized directive that is implemented numerous times within a single webpage (AngularJS)

Recently, I designed a unique directive that includes various inputs and dropdowns. To ensure proper binding between the outer and inner scopes for two-way data binding, I implemented an isolate scope. This setup allows me to reuse the directive multiple t ...

Export was not discovered, yet the names are still effective

There seems to be a slight issue that I can't quite figure out at the moment... In my Vue project, I have a file that exports keycodes in two different formats: one for constants (allCodes) and another for Vue (keyCodes): export default { allCodes ...

Use jQuery ajax to send form data and display the received information in a separate div

I'm working on a PHP test page where I need to submit a form with radios and checkboxes to process.php. The result should be displayed in #content_result on the same page without refreshing it. I attempted to use jQuery Ajax for this purpose, but noth ...

Load the index file using any URL parameter in the Express.js Router's "catchall" feature

I have a simple setup for my project, including server.js file in the root directory with the following code: app.use('/', express.static(__dirname + '/public/')); In addition, there is a public folder containing index.html, styles, a ...

The process of JavaScript for detecting and extracting text from

After much searching, I stumbled upon this intriguing piece of JavaScript code at this location. Curiously, I was able to remove a few eggs using the following script: var eggCoordinates = []; for (var i = 0; i < 5; i++) { eggCoordinates.push(new E ...

Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

What is the best way to verify the number of values stored within a variable in JavaScript?

My goal is to calculate the sum of 6 values by inputting them into a single field using a button. To achieve this, I am seeking knowledge on how to determine the number of values contained within a variable. This will allow me to implement an "if" conditi ...

Extracting data from a website without the need to constantly refresh

I am looking to extract data from a specific website, accessible at the following URL: After obtaining the URL with firebug, I successfully extracted data from the HTML code using urlopen and regexes. However, the current process requires me to perform an ...

managing a Cross-Origin AJAX redirect

We are currently in the process of developing a RESTful API to be hosted on server x.foo.com. The client-side html applications, which are built using jQuery, will be hosted on y.foo.com. To address cross-domain issues, we have implemented the Access-Cont ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

Encountered a problem when injecting the angularjs $location service

I'm having some trouble getting the $location service to work in this code snippet: <script type="text/javascript> var $injector = angular.injector(['ng', 'kinvey', 'app.constants']); $in ...

Issue with OpenLayers Icon not appearing on screen

I just finished creating a SpringBoot app using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and packaging it as an executable JAR file. Within this app, I have integrated OpenLayers 4 library to display a map with an Icon. Howeve ...

Setting URL parameters in a POST request: A guide

Currently, the data in question is structured as JSON within this code snippet. However, I've received feedback indicating that it should actually be implemented as URL parameters. I'm currently facing some difficulties with modifying this to fit ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

What is the best way to use Promise.all() to delay the return of an array that is currently being constructed within the function?

In the following code block, I am trying to set an array as the value for a local variable by calling a function that returns an array. The issue arises because the Promises in the second function are not resolved until after the array has been returned to ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

What are the ways to convert canvas animations into gif or webm formats?

I've written a function to capture each frame for the GIF, but I'm experiencing laggy output and crashes as the data increases. Any recommendations? function generateGifFromImages(imageList, frameRate, fileName, scaling) { gifshot.createGIF({ ...

How can I relocate an object to a different position within THREE.JS?

I'm trying to figure out how to move one object to the position of another object. I found some suggestions online to use the TWEEN library, but I'm having trouble integrating it into my code. Any help would be greatly appreciated :) <scrip ...

Freshly updated chatroom!

I want to develop an ajax-powered chatroom for my website and have tried yshout, which I found to be effective but prone to crashing with too many connections. How can I optimize this chatroom to use minimal resources while still delivering top performanc ...