Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 298
hippietrail Avatar asked Jan 09 '13 23:01

hippietrail


3 Answers

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

like image 87
Musa Avatar answered Nov 04 '22 00:11

Musa


Use .html() instead of .text()

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

OR use the DOM method .innerText

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

Check Fiddle

like image 44
Sushanth -- Avatar answered Nov 04 '22 00:11

Sushanth --


You can use the replaceWith() function.

$("br").replaceWith(" ");
like image 3
Mims H. Wright Avatar answered Nov 04 '22 02:11

Mims H. Wright