0

I have a problem resetting the content for the divs in the view where I show a single email. For some reason the divs console.log out as "null", while the parent element for some reason works to console.log. Can somebody help me understand why it don't work?

function show_email(id) {

  
    // Show the mailbox and hide other views
    document.querySelector('#email-view').style.display = 'block';
    document.querySelector('#emails-view').style.display = 'none';
    document.querySelector('#compose-view').style.display = 'none';


    // THESE DON'T WORK AS THEY DISPLAY AS "NULL"

    //document.querySelector('#read-timestamp').innerHTML = ""
    //document.querySelector('#read-sender').innerHTML = ""
    //document.querySelector('#read-recipients').innerHTML = ""
    //document.querySelector('#read-body').innerHTML = ""


    fetch(`/emails/${id}`)
    .then(response => response.json())
    .then(email => {
      subject = email.subject
      sender = email.sender
      recipients = email.recipients
      timestamp = email.timestamp
      body = email.body

      // Create div for each mail
    let element = document.createElement("div");
    element.setAttribute("id", "element")
    element.classList.add("mailcontainer")

    // Create a top container for title and time
    let topcontainer = document.createElement("div")
    topcontainer.classList.add("topcontainer")
    element.appendChild(topcontainer)

      // Create a top container for title and time
      let subjectp = document.createElement("p")
      subjectp.classList.add("subject")
      subjectp.setAttribute("id", "read-subject")
      subjectp.innerHTML = subject
      topcontainer.appendChild(subjectp)

      // Create a top container for title and time
      let timestampp = document.createElement("p")
      timestampp.classList.add("timestamp")
      subjectp.setAttribute("id", "read-timestamp")
      timestampp.innerHTML = timestamp
      topcontainer.appendChild(timestampp)

    // Create a top container for title and time
    let senderp = document.createElement("p")
    senderp.classList.add("sender")
    subjectp.setAttribute("id", "read-sender")
    senderp.innerHTML = `From: ${sender}`
    element.appendChild(senderp)

    // Create a top container for title and time
    let recipientp = document.createElement("p")
    recipientp.classList.add("recipients")
    subjectp.setAttribute("id", "read-recipients")
    recipientp.innerHTML = `To: ${recipients}`
    element.appendChild(recipientp)

    // Create a top container for title and time
    let bodyp = document.createElement("p")
    bodyp.classList.add("bodyp")
    subjectp.setAttribute("id", "read-body")
    bodyp.innerHTML = body
    element.appendChild(bodyp)

    // Append the whole element to the email view
    document.querySelector("#email-view").append(element)

    let elements = document.querySelector("#element")
    
    // THIS ACTUALLY PRINT OUT THE ELEMT
    console.log(elements)

    // BUT THIS PRINT OUT AS "NULL"
    let recipientss = document.querySelector("#read-recipients")
    console.log(recipientss)

    })
}

HTML

{% extends "mail/layout.html" %}
{% load static %}

{% block body %}
    <h2>{{ request.user.email }}</h2>

    <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button>
    <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button>
    <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button>
    <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button>
    <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a>
    <hr>

    <div id="emails-view">
    </div>

    <div id="email-view">
    </div>

    <div id="compose-view">
        <h3>New Email</h3>
        <form id="compose-form">
            <div class="form-group">
                From: <input disabled class="form-control" value="{{ request.user.email }}">
            </div>
            <div class="form-group">
                To: <input id="compose-recipients" class="form-control">
            </div>
            <div class="form-group">
                <input class="form-control" id="compose-subject" placeholder="Subject">
            </div>
            <textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
            <button id="submit" type="button" class="btn btn-primary"/>Submit</button>
        </form>
    </div>
{% endblock %}

{% block script %}
    <script src="{% static 'mail/inbox.js' %}"></script>
{% endblock %}
2
  • Could you add your html
    – Vsjain
    Commented Mar 25, 2021 at 15:45
  • @Vsjain - done!
    – Alexander
    Commented Mar 25, 2021 at 17:12

1 Answer 1

0

Solved it. I had used subjectp instead of each div when assigning the IDs. Also went with using classes instead and had to implement a for loop to loop over the divs to clear its innerhtml content.

   document.addEventListener('DOMContentLoaded', function() {

  // Use buttons to toggle between views
  document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
  document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
  document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
  document.querySelector('#compose').addEventListener('click', compose_email);
  document.querySelector('#submit').addEventListener('click', send_email);

  // By default, load the inbox
  load_mailbox('inbox');
});

function compose_email() {

  // Show compose view and hide other views
  document.querySelector('#email-view').style.display = 'none';
  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 = '';
}

function load_mailbox(mailbox) {
  
  // Show the mailbox and hide other views
  document.querySelector('#email-view').style.display = 'none';
  document.querySelector('#emails-view').style.display = 'block';
  document.querySelector('#compose-view').style.display = 'none';


  // Show the mailbox name
  document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;

  // Get data in the mailbox
  fetch(`/emails/${mailbox}`)
  .then(response => response.json())
  .then(emails => { 

    emails.forEach(email => {
      sender = email.sender
      subject = email.subject
      timestamp = email.timestamp
      id = email.id
      read = email.read
      recipients = email.recipients

      // Create div for each mail
      const element = document.createElement("div");
      element.setAttribute("id", id)
      element.classList.add("maildiv")

      // Mark read emails in the inbox mailbox
      if (read && mailbox === "inbox") {
        element.style.backgroundColor = "#e8e8e8"
      }

      // Create a top container for title and time
      const topcontainer = document.createElement("div")
      topcontainer.classList.add("topcontainer")
      element.appendChild(topcontainer)

      if (mailbox === "inbox") {
        // Create paragraph for sender content
        senderp = document.createElement("P")
        senderp.classList.add("sender")
        senderp.innerHTML = `From: ${sender}`
        topcontainer.appendChild(senderp)
      }

      if (mailbox === "sent" ) {
        // Create paragraph for recipients content
        recipientsp = document.createElement("P")
        recipientsp.classList.add("recipients")
        recipientsp.innerHTML = `To: ${recipients}`
        topcontainer.appendChild(recipientsp)
      }

      if (mailbox === "archive") {

        // Create paragraph for sender content
        senderp = document.createElement("P")
        senderp.classList.add("sender")
        senderp.innerHTML = `From: ${sender}`
        topcontainer.appendChild(senderp)

        // Create paragraph for recipients content
        recipientsp = document.createElement("P")
        recipientsp.classList.add("recipients")
        recipientsp.innerHTML = `To: ${recipients}`
        topcontainer.appendChild(recipientsp)

      }

      // Create paragraph for timestamp content
      timestampp = document.createElement("P")
      timestampp.classList.add("timestamp")
      timestampp.innerHTML = timestamp
      topcontainer.appendChild(timestampp)

      // Create paragraph for subject content
      subjectp = document.createElement("P")
      subjectp.classList.add("subject")
      subjectp.innerHTML = subject
      element.appendChild(subjectp)

      // Append the whole element to the email view
      document.querySelector("#emails-view").append(element)

      // Add event listener to each mail
      element.addEventListener("click", (e) => {
        target = e.currentTarget
        thisid = target.getAttribute("id")
        show_email(thisid)
      });
    });
  })
}

function show_email(id) {

  
    // Show the mailbox and hide other views
    document.querySelector('#email-view').style.display = 'block';
    document.querySelector('#emails-view').style.display = 'none';
    document.querySelector('#compose-view').style.display = 'none';
    
    let counts = document.querySelectorAll('.read-timestamp').length 
    
    if (counts > 0) {

      for (let i = 0; i < counts; i++ ) {

        document.querySelectorAll('.read-timestamp')[i].innerHTML = ""
        document.querySelectorAll('.read-sender')[i].innerHTML = ""
        document.querySelectorAll('.read-recipients')[i].innerHTML = ""
        document.querySelectorAll('.read-body')[i].innerHTML = ""
        document.querySelectorAll('.read-subject')[i].innerHTML = ""
        document.querySelectorAll('.mailcontainer')[i].innerHTML = ""

      }
    }
    
    fetch(`/emails/${id}`)
    .then(response => response.json())
    .then(email => {
      subject = email.subject
      sender = email.sender
      recipients = email.recipients
      timestamp = email.timestamp
      body = email.body

      // Create div for each mail
    element = document.createElement("div");
    element.setAttribute("id", "element")
    element.classList.add("mailcontainer")

    // Create a top container for title and time
    let topcontainer = document.createElement("div")
    topcontainer.classList.add("topcontainer")
    element.appendChild(topcontainer)

      // Create a top container for title and time
      let subjectp = document.createElement("p")
      subjectp.classList.add("read-subject")
      subjectp.innerHTML = `Subject: ${subject}`
      topcontainer.appendChild(subjectp)

      // Create a top container for title and time
      let timestampp = document.createElement("p")
      timestampp.classList.add("read-timestamp")
      timestampp.innerHTML = timestamp
      topcontainer.appendChild(timestampp)

    // Create a top container for title and time
    let senderp = document.createElement("p")
    senderp.classList.add("read-sender")
    senderp.innerHTML = `From: ${sender}`
    element.appendChild(senderp)

    // Create a top container for title and time
    let recipientp = document.createElement("p")
    recipientp.classList.add("read-recipients")
    recipientp.innerHTML = `To: ${recipients}`
    element.appendChild(recipientp)

    // Create a top container for title and time
    let bodyp = document.createElement("p")
    bodyp.classList.add("bodyp")
    bodyp.classList.add("read-body")
    bodyp.innerHTML = body
    element.appendChild(bodyp)

    // Append the whole element to the email view
    document.querySelector("#email-view").append(element)



    })
}


function send_email() {

  // Get values from fields
  recipients = document.querySelector('#compose-recipients').value;
  subject = document.querySelector('#compose-subject').value;
  body = document.querySelector('#compose-body').value;

  // Send POST request with the data from the fields 
  fetch("/emails", {
    method: "POST",
    body: JSON.stringify({
      recipients: recipients,
      subject: subject,
      body: body
    }),
  })
  .then(response => response.json())
  .then(result => {
    console.log(result)
  })

  // Redirect to sent mailbox
  load_mailbox('sent');

  
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .