Can't add event when iterate a NodeList using javascript

I’m trying to iterate a NodeList  object using javascript, and i want to a click event to eatch 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 work !

How can i fix this ?

>Solution :

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>

wrap your logic in

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

Leave a Reply