1
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!

3 Answers 3

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

1

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.