Reputation: 3794
function toText()
{
var convertHTML =$('#mainContent').html();
var ele = $(convertHTML + " > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
My aim is to replace the following content
<div id="mainContent">
test
<br>
1234
<br>
<span class="underline">test</span>
<br>
<span class="underline">1234</span>
</div>
And want my function to output test <br> 1234 <br> test <br> 1234
This is why i cant just use text() as it takes away the <br>
aswell!
Upvotes: 1
Views: 564
Reputation: 150030
You were taking the html string returned from $("#mainContent").html()
and trying to use it as part of the selector on the next line, when really the selector you need is "#mainContent > span"
.
Try this instead:
function toText()
{
$("#mainContent > span").replaceWith(function(){ return $(this).text(); });
}
You don't need an .each()
loop: if you pass a function to .replaceWith()
that function is called once for each element in your jQuery object and your return value is used as the replacement for the current element.
Demo: http://jsfiddle.net/7xKzP/
Upvotes: 1
Reputation: 7100
convertHTML
from var convertHTML =$('#mainContent').html();
is not a jQuery object
You will have to write
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
Reason :
$('#mainContent').html();
will return you the string
not a jQuery object for $.each
to work.
var ele = $(convertHTML + " > span")
would mean
var ele = $("test<br>1234<br><span class="underline">test</span><br><span class="underline">1234</span>" + " > span")
Upvotes: 1
Reputation: 9975
Try it like this:
function toText()
{
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
You where using an entire block of html as a jQuery selector :)
Upvotes: 3