Reputation: 782
I want to create a new paragraph in a div:
And I want to use new lines in the paragraph. I am escaping them using \n but they are creating new lines. What am I doing wrong?
var oNewP = document.createElement("p");
var oText = document.createTextNode("Harry Huy\nPresident\n283.423.6431\[email protected]");
oNewP.appendChild(oText);
document.body.appendChild(oNewP);
var Test = document.getElementById('Test');
Test.appendChild(oNewP);
http://jsfiddle.net/4qvydycf/4/
Upvotes: 0
Views: 7085
Reputation: 3953
just use the tag pre and leave the paragraph as you concatenate it with \n like this:
var oNewP = document.createElement("pre");
var oText = document.createTextNode("Harry
Huy\nPresident\n283.423.6431\[email protected]");
oNewP.appendChild(oText);
document.body.appendChild(oNewP);
var Test = document.getElementById('Test');
Test.appendChild(oNewP);
Upvotes: 0
Reputation: 1571
The \n
is not an HTML element, use <br />
element instead. However the createTextNode
is not render the text as HTML, so you need to do something like this:
var Test = document.getElementById('Test');
Test.appendChild(document.createTextNode("Harry Huy"));
Test.appendChild(document.createNode('br'));
Test.appendChild(document.createTextNode("President"));
Test.appendChild(document.createNode('br'));
Test.appendChild(document.createTextNode("283.423.6431"));
Test.appendChild(document.createNode('br'));
Test.appendChild(document.createTextNode("[email protected]"));
Upvotes: 4
Reputation: 943579
A new line in a text does doesn't usually create a new line in an HTML document. It doesn't matter that you are using JavaScript. The result is the same as having…
<p>Harry Hun
President
… in the HTML. The new line is treated like any other whitespace (new line, tab, space) character.
You deal with this in the same way that you do in HTML. Either:
br
elements between thenwhite-space
propertywhite-space
property by default (like pre
).Upvotes: 4