Reputation: 7392
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.
Upvotes: 17
Views: 22264
Reputation: 14749
If you don’t mind a destructive (“modifying the HTML code”) operation:
$("#id").find("br").replaceWith("\n").end().text()
Upvotes: 0
Reputation: 707158
.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.
Upvotes: 22