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:

[email protected]

jan 10, 2009

subject: happy

body: hello!

However, I am getting this in the webpage: [email protected] <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.

4
  • <p> and <br> should create newlines when the HTML is rendered. Commented Aug 17, 2021 at 22:41
  • However, even better is to understand that newlines are "just whitespace" in HTML, and use CSS to lay out your content. You don't want newlines. You want HTML elements with classes and attributes that let you target them with CSS. Commented Aug 17, 2021 at 22:42
  • Using append is for created elements in a variable. You are appending a string so it would show a string. You should use innerHTML. Commented Aug 17, 2021 at 23:07
  • Thanks everyone. This is super helpful Commented Aug 18, 2021 at 8:10

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.