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!
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:
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/