Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading