Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery text(), interpret<br> as new line

Tags:

jquery

Getting an element of the DOM like this

$('#id').content().text();

Problem arises with

If it gets this:

<p>Hello</p>
<p><br></p>
<p>World</p>

Naturally in Html looks like:

Hello 

World

But this jquery .text() method returns: HelloWorld

How to interpret <br> as new line? <-> How to get the text exactly as I see it in HTML?

.html() gives all the HTML tags, which I don't want. I just need the plain text with spaces, if possible.

like image 374
jacktrades Avatar asked Aug 10 '12 16:08

jacktrades


1 Answers

.text() is plain text without formatting. It is literally the concatenation of the text nodes without any other HTML codes (including new lines which are represented by <br> or <p> tags, not by newlines).

.html() is the exact HTML of a container tag.

If you use this, it will get you an approximation of your text with new lines:

var item = document.getElementById("id");
var text = item.innerText || item.textContent;

It's looking at both .textContent and .innerText due to browser compatibility issues.

See http://jsfiddle.net/jfriend00/Xs5P3/ for a working demo.

A Google search for "HTML to text conversion" gives a lot of options to investigate.

like image 163
jfriend00 Avatar answered Sep 24 '22 04:09

jfriend00