Anders
Anders

Reputation: 200

JavaScript appendChild text node doesn't break line

a JavaScript n00b here...
I'm generating some html code in javascript, that is going to be displayed as code via the prism HTML markup plugin. The code is dynamically added to a <pre> tag on a button click.

My javascript code is as below. It is the text in line 2, where I need a line break. I have tried /n but that doesn't work it just makes a space.

var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);

Below is the text string I'm trying to create, where a line break is made where the text LINEBREAK HERE is.

<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>

Upvotes: 2

Views: 952

Answers (2)

Asons
Asons

Reputation: 87201

Is it something like this you are looking for?

By using String.fromCharCode(10) you can insert a line break and with the pre tag (or div having white-space: pre-wrap) the line break will be visible/shown.

var elementNameFinal = "elementname", fieldNameFinal = "fieldname";

var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>" + String.fromCharCode(10) + "<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>";

document.getElementById("dropdown-code").appendChild(startLabelTag);
<pre id="dropdown-code"></pre>

Side note

You can of course use a div as well, having the CSS rule Niet the Dark Absol suggested.

<div id="dropdown-code"></div>

#dropdown-code {
  white-space: pre-wrap;
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Add white-space: pre-wrap to the container's CSS.

After all, if you type a newline in your HTML source, do you get a blank line in the result? Nope. Not without making whitespace significant through CSS.

Upvotes: 0

Related Questions