0

I have the following in my JS file:

const emailCol = `${email.sender} <br> ${email.subject}  <br>   ${email.timestamp}`
  const moo  = document.createElement('br');
  console.log("HERE!!", emailCol)
  em.innerHTML = emailCol;


  const para = document.createElement("p");
const node = document.createTextNode(`${email.sender} <br></br> `);
para.appendChild(node);
const node1 = document.createTextNode(`${email.timestamp} <br>`);
para.appendChild(node1);
const node2 = document.createTextNode(`${email.subject}</p><p>`);
para.appendChild(node2);
const node3 = document.createTextNode(`${email.body}</p><p>`);
para.appendChild(node3);

const element = document.getElementById("div1");
element.appendChild(para);

My aim is to render in HTML something like:

John@sender.com

jan 10, 2009

subject: happy

body: hello!

However, I am getting this in the webpage: John@sender.com <br></br> jan 10, 2009 <br>qww</p><p>body: hello!</p><p> with no line breaks.

How do I make these breaks become new lines when the webpage renders from JavaScript to HTML?

I tried this Stack Overflow post, but I can't get the /n to work.

Katie Melosto
  • 1,047
  • 2
  • 14
  • 35

1 Answers1

1

createTextNode is for creating text, not HTML elements like <br> or <p>. Try this:

const para1 = document.createElement("p");
para.appendChild(document.createTextNode(`${email.sender}`));
para.appendChild(document.createElement("br"));
para.appendChild(document.createTextNode(`${email.timestamp}`);
para.appendChild(document.createElement("br"));
para.appendChild(document.createTextNode(`${email.subject}`);

const para2 = document.createElement("p");
para2.appendChild(document.createTextNode(`${email.body}`);

const element = document.getElementById("div1");
element.appendChild(para);
element.appendChild(para2);
edemaine
  • 2,699
  • 11
  • 20