Harry
Harry

Reputation: 782

new line within createTextNode

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

Answers (3)

Rida Rezzag
Rida Rezzag

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

rogelio
rogelio

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

Quentin
Quentin

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:

  • Use multiple text nodes with br elements between then
  • Use the CSS white-space property
  • Use an element that applies the white-space property by default (like pre).

Upvotes: 4

Related Questions