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>
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
Use .html()
instead of .text()
$('#foo').html();
OR use the DOM method .innerText
$('#foo')[0].innerText ;
Check Fiddle
You can use the replaceWith()
function.
$("br").replaceWith(" ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With