Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a javascript textNode element on a newline

Tags:

javascript

I insert several textNodes in javascript, and can't figure out how to separate them with carriage returns. I've tried putting "\n", "\r", and "
" but none of them work

var textNode = document.createTextNode("Node on line 1"); element.appendChild(textNode);  textNode = document.createTextNode("Node on line 2"); element.appendChild(textNode); 

I want this to appear as:

Node on line 1

Node on line 2

NOT

Node on line 1Node on line2

Any tips on how I can accomplish this ?

like image 795
Anthony Avatar asked Nov 16 '11 05:11

Anthony


People also ask

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

Use <br> to separate them as like this

var br = document.createElement("br"); element.appendChild(br); 
like image 103
Selvakumar Ponnusamy Avatar answered Sep 27 '22 17:09

Selvakumar Ponnusamy


Rendering engines don't consider linefeed and carriage return to be rendered. Better if you use a <br /> like this:

var textNode = document.createTextNode("Node on line 1"); element.appendChild(textNode);  var linebreak = document.createElement('br'); element.appendChild(linebreak);  var linebreak = document.createElement('br'); element.appendChild(linebreak);  textNode = document.createTextNode("Node on line 2"); element.appendChild(textNode); 

Thanks Doug Owings. Also http://jsfiddle.net/Q8YuH/3/

like image 22
Abdul Munim Avatar answered Sep 27 '22 15:09

Abdul Munim