anon123123
anon123123

Reputation: 25

Getting the element id of a click event with dynamic content

Learning JS and my project currently is to create an inbox (following the CS50 Web Application course). This is a single-page application and looks like this:

What it currently looks like The emails are dynamically generated as I compose them and send them to [email protected].

And this is the code I wrote to get the dynamic content, in nested divs.

// Get emails for inbox
  if (mailbox === 'inbox') {
    fetch('/emails/inbox')
      .then(response => response.json())
      .then(emails => {
        console.log(emails);

        let inbox_container = document.createElement('div');

        inbox_container.setAttribute("id", "inbox-container");

        document.querySelector('#emails-view').append(inbox_container);

        for (let i = 0; i < emails.length; i++) {

          let email_id = i;

          let email_header = document.createElement('div');
          email_header.setAttribute("class", "email-header")
          email_header.setAttribute("id", email_id);
          email_header.addEventListener('click', function(event) {
            console.log(event);
          });

          let sender = document.createElement('div');
          sender.setAttribute("class", "email-header-sender");
          sender.appendChild(document.createTextNode(emails[i].sender));

          let subject = document.createElement('div');
          subject.setAttribute("class", "email-header-subject");
          subject.appendChild(document.createTextNode(emails[i].subject));

          let timestamp = document.createElement('div');
          timestamp.setAttribute("class", "email-header-timestamp");
          timestamp.appendChild(document.createTextNode(emails[i].timestamp));

          email_header.appendChild(sender);
          email_header.appendChild(subject);
          email_header.appendChild(timestamp);

          document.querySelector("#inbox-container").append(email_header);
        }
      });
  }

What I am trying to do is add a click listener to each email-header div as I create them, so I assigned them a unique ID that is simply a number starting with 0.

However, I am stuck on trying to get this ID in my click event. In the console log of the event, I can't find this ID and there's so much more excessive information. That leads me to think there must be a better way to implement this.

Any ideas?

Upvotes: 0

Views: 864

Answers (1)

Zuckerberg
Zuckerberg

Reputation: 2161

You can get id property of each new element easily like:

 email_header.addEventListener('click', function(event) {
     console.log( event.target.id );
 });

Or like,

 email_header.addEventListener('click', function(event) {
     console.log( this.id );
 });

Upvotes: 1

Related Questions