mowwwalker
mowwwalker

Reputation: 17392

Adding a new line to text string with jquery .text() method

When I do:

function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    $("#divtext").text(text);   
}

It all appears on one line. When I do:

function testtext()
{
    var text = "test line 1\n\
    test line 2"
    ;
    document.getElementById("divtext").innerText = text;    
}

It works fine...

Upvotes: 2

Views: 11762

Answers (3)

Sukesh Chand
Sukesh Chand

Reputation: 3057

Use $("#divtext").html(text);

Instead of $("#divtext").text(text);

Upvotes: 3

joseph
joseph

Reputation: 780

The text() method will do an HTML escape. There are some workarounds on the API page, but perhaps the text() method isn't best suited for what you want to do?

http://api.jquery.com/text/

Upvotes: 0

user113716
user113716

Reputation: 322612

If you're wondering why, it's because jQuery creates a new text node using document.createTextNode, passing your string as the argument.

This apparently behaves differently than innerText, though it seems to behave the same as setting .textContent and as explicitly setting the value of a textNode through .nodeValue or .data.

Upvotes: 0

Related Questions