hippietrail
hippietrail

Reputation: 16966

jQuery .text() equivalent that converts <br> tags to whitespace

It's trivial to get the text from a jQuery selection:

<span id="foo">hello world</span>

$('#foo').text();

hello world

But when the jQuery selection contains <br> tags they are conceptually newlines, which are whitespace. Unfortunately .text() strips them completely:

<span id="foo">hello<br>world</span>

$('#foo').text();

helloworld

How can I extract the text from such a span such that it results in hello world instead?

Of course this is a trivial example invented to keep the problem clear. A real answer will need to be "equivalent to .text()" and handle arbitrary HTML of course. Here's a slightly more tricky example, also made up:

<div id="foo"><span class="bar"><em>hello</em><br></span>world</div>

Upvotes: 15

Views: 7014

Answers (3)

Mims H. Wright
Mims H. Wright

Reputation: 3037

You can use the replaceWith() function.

$("br").replaceWith(" ");

Upvotes: 3

Musa
Musa

Reputation: 97672

As Mims suggest use replaceWith() to change the <br> to spaces, but as not to alter the original element use clone() to make a clone of the element.

var foo = $("#foo").clone();
foo.find("br").replaceWith(" ");
var text = foo.text();

DEMO

Upvotes: 12

Sushanth --
Sushanth --

Reputation: 55740

Use .html() instead of .text()

$('#foo').html();

OR use the DOM method .innerText

$('#foo')[0].innerText ;

Check Fiddle

Upvotes: 12

Related Questions