Polly
Polly

Reputation: 657

Put a new line in <p> tag

I try to put a new line in a <p> (html code):

<p id="text_folder"><p>

This is my jquery code:

$('#text_folder').text("first"+"\n"+"second");

But in my <p> tag the result is
first second
and not:
first
second
Anyone can help me?

Upvotes: 15

Views: 47159

Answers (4)

Vikram
Vikram

Reputation: 720

Write code like this

$('#text_folder').html("first<br>second");

Upvotes: 1

Remo
Remo

Reputation: 4387

You are working with HTML and thus have to use html() instead of text()

$('#text_folder').html("first<br>second");

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074138

In HTML, all whitespace characters (including newlines) are interpreted as spaces. To put a line break in a p element, you use a br element:

$("#text_folder").html("first<br>second");

If your "first" and "second" are externally-sourced (from the user, etc.), you'll want to make sure that you deal with any special HTML characters in them first. There are a couple of ways to do that; I find replace the simplest of them:

function escapeHTML(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}

so then

var first = /*...get input from user or whatever...*/;
var second = /*...get input from user or whatever...*/;
$("#text_folder").html(escapeHTML(first) + "<br>" + escapeHTML(second));

Upvotes: 5

Chetan Sanghani
Chetan Sanghani

Reputation: 2111

('#text_folder').html("first"+"<br />"+"second")

try this

Upvotes: 11

Related Questions