Faraz
Faraz

Reputation: 6265

Linebreaks not rendering in HTML

I am creating H5 dynamically and rendering a String. I am unable to create new lines. This is what I have tried so far:

var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);

I have also tried <br> but it just renders as is. How do I create new lines?

Upvotes: 0

Views: 59

Answers (2)

Renzo Calla
Renzo Calla

Reputation: 7686

A textnode element doesn't interpret html, that is why your html is written as text. On the other hand the \n will be inserted in a textnode but it won't work in html H5 tag.A solution is to create a "pre" tag instead of h5, or use the innerHTMl property...

var h5 = document.createElement('h5');
h5.innerHTML="City: Chicago<br>State: Illinois";
document.body.appendChild(h5);

Upvotes: 2

Derek Pollard
Derek Pollard

Reputation: 7165

Problem

Linebreaks that aren't HTML only render in pre elements and those with the special pre style

Solution

Use the white-space: pre; style

Using a separate CSS rule

var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
h5 {
  white-space: pre;
}

Javascript only solution

var h5 = document.createElement('h5');
h5.style.whiteSpace = 'pre';
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);

Hope this helps!

Upvotes: 4

Related Questions