title: Unable to queryselector HTML elements dynamically created by JS
body: <p>I am trying to do my course project so I am a newbie to this.</p>
  <p>The project is creating an emailing website.</p>
  <p>So after listing the emails a user should be able to click on any email to view that email. But since the list of emails is dynamically generated by JS:</p>
  <pre><code>if (mailbox == &quot;sent&quot;) {
      fetch('/emails/sent')
      .then(response =&gt; response.json())
      .then(emails =&gt; {
  
        for (let i=0; i&lt;emails.length; i++) {
          const id = emails[i].id;
          const sender = emails[i].sender;
          const subject = emails[i].subject;
          const timestamp = emails[i].timestamp;
          document.querySelector('#emails-view').innerHTML += `
          &lt;div&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;div data-id=&quot;${id}&quot; class=&quot; row email-box&quot;&gt;
                &lt;div class=&quot; col-2 email-sender&quot;&gt;${sender}&lt;/div&gt;
                &lt;div class=&quot;col-3 email-subject&quot;&gt;${subject}&lt;/div&gt;
                &lt;div class=&quot;col-7 email-timestamp&quot;&gt;${timestamp}&lt;/div&gt;
              &lt;/div&gt;
            &lt;/a&gt;
          &lt;/div&gt;`;
        }
      })
    }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/C7fv1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C7fv1.png" alt="enter image description here" /></a></p>
  <p>queryselector is not working:</p>
  <pre><code>  document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('#emails-view &gt; div:nth-child(2) &gt; div').foreach(function(email) {
        email.onclick = function() {
          console.log('clicked')
        }
      });
    });
  </code></pre>
  <p>I tried this on a simple h3 thats also dynamically created and it still doesnt work.</p>
  <pre><code>  document.querySelector('#emails-view').innerHTML = `&lt;h3 id=&quot;h3&quot;&gt;${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}&lt;/h3&gt;`;
  </code></pre>
  <pre><code>  document.querySelector('h3').addEventListener('click', () =&gt; console.log('clicked'));
  </code></pre>
  <p>Here us the full code:</p>
  <pre><code>document.addEventListener('DOMContentLoaded', function() {
  
    // Use buttons to toggle between views
    document.querySelector('h3').addEventListener('click', () =&gt; console.log('clicked'));
    
  
  
    document.querySelector('#inbox').addEventListener('click', () =&gt; load_mailbox('inbox'));
    document.querySelector('#sent').addEventListener('click', () =&gt; load_mailbox('sent'));
    document.querySelector('#archived').addEventListener('click', () =&gt; load_mailbox('archive'));
    document.querySelector('#compose').addEventListener('click', compose_email);
  
    // By default, load the inbox
    load_mailbox('inbox');
  });
  
  function compose_email() {
  
    // Show compose view and hide other views
    document.querySelector('#emails-view').style.display = 'none';
    document.querySelector('#compose-view').style.display = 'block';
  
    // Clear out composition fields
    document.querySelector('#compose-recipients').value = '';
    document.querySelector('#compose-subject').value = '';
    document.querySelector('#compose-body').value = '';
  
    document.querySelector('#compose-form').onsubmit = () =&gt; {
      
      fetch('/emails', {
        method: 'POST',
        body: JSON.stringify({
            recipients: document.querySelector('#compose-recipients').value,
            subject: document.querySelector('#compose-subject').value,
            body: document.querySelector('#compose-body').value
        })
      })
      .then(response =&gt; response.json())
      .then(result =&gt; {
          // Print result
          console.log(result);
      })
      
      load_mailbox('sent')
      return false;    
    }
  }
  
  function load_mailbox(mailbox) { 
  
    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('#emails-view &gt; div:nth-child(2) &gt; div').foreach(function(email) {
        email.onclick = function() {
          console.log('clicked')
        }
      });
    });
  
    // Show the mailbox and hide other views
    document.querySelector('#emails-view').style.display = 'block';
    document.querySelector('#compose-view').style.display = 'none';
  
    // Show the mailbox name
    document.querySelector('#emails-view').innerHTML = `&lt;h3 id=&quot;h3&quot;&gt;${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}&lt;/h3&gt;`;
  
    if (mailbox == &quot;sent&quot;) {
      fetch('/emails/sent')
      .then(response =&gt; response.json())
      .then(emails =&gt; {
  
        for (let i=0; i&lt;emails.length; i++) {
          const id = emails[i].id;
          const sender = emails[i].sender;
          const subject = emails[i].subject;
          const timestamp = emails[i].timestamp;
          document.querySelector('#emails-view').innerHTML += `
          &lt;div&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;div data-id=&quot;${id}&quot; class=&quot; row email-box&quot;&gt;
                &lt;div class=&quot; col-2 email-sender&quot;&gt;${sender}&lt;/div&gt;
                &lt;div class=&quot;col-3 email-subject&quot;&gt;${subject}&lt;/div&gt;
                &lt;div class=&quot;col-7 email-timestamp&quot;&gt;${timestamp}&lt;/div&gt;
              &lt;/div&gt;
            &lt;/a&gt;
          &lt;/div&gt;`;
        }
      })
    }
  
    else if (mailbox == &quot;inbox&quot;) {
      fetch('/emails/inbox')
      .then(response =&gt; response.json())
      .then(emails =&gt; {
      
        for (let i=0; i&lt;emails.length; i++) {
          const id = emails[i].id;
          const sender = emails[i].sender;
          const subject = emails[i].subject;
          const timestamp = emails[i].timestamp;
          document.querySelector('#emails-view').innerHTML += `
          &lt;div&gt;
              &lt;div data-id=&quot;${id}&quot; class=&quot; row email-box&quot;&gt;
                &lt;div class=&quot; col-2 email-sender&quot;&gt;${sender}&lt;/div&gt;
                &lt;div class=&quot;col-3 email-subject&quot;&gt;${subject}&lt;/div&gt;
                &lt;div class=&quot;col-7 email-timestamp&quot;&gt;${timestamp}&lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;`;
        }
      })
    }
  
    else if (mailbox == &quot;archive&quot;) {
      fetch('/emails/archive')
      .then(response =&gt; response.json())
      .then(emails =&gt; {
  
        for (let i=0; i&lt;emails.length; i++) {
          const id = emails[i].id;
          const sender = emails[i].sender;
          const subject = emails[i].subject;
          const timestamp = emails[i].timestamp;
          document.querySelector('#emails-view').innerHTML += `
          &lt;div&gt;
            &lt;a href=&quot;#&quot;&gt;
              &lt;div data-id=&quot;${id}&quot; class=&quot;row email-box&quot;&gt;
                &lt;div class=&quot; col-2 email-sender&quot;&gt;${sender}&lt;/div&gt;
                &lt;div class=&quot;col-3 email-subject&quot;&gt;${subject}&lt;/div&gt;
                &lt;div class=&quot;col-7 email-timestamp&quot;&gt;${timestamp}&lt;/div&gt;
              &lt;/div&gt;
            &lt;/a&gt;
          &lt;/div&gt;`;
        }
      })
    }
    document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('.email-box').addEventListener('click', () =&gt; console.log('clicked'));
    });
  
  }
  
  function view_email(id) { 
  
    fetch(`/emails/${id}`)
    .then(response =&gt; response.json())
    .then(email =&gt; {
      // Print email
      console.log(email);
  
      // ... do something else with email ...
    });
  }
  </code></pre>