Reputation: 6265
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
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
Reputation: 7165
Linebreaks that aren't HTML only render in pre
elements and those with the special pre
style
Use the white-space: pre;
style
var h5 = document.createElement('h5');
h5.appendChild(document.createTextNode("City: Chicago\nState: Illinois"));
document.body.appendChild(h5);
h5 {
white-space: pre;
}
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