DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

jQuery get text

I have a function that returns some html like this:

return ("<span class='opt'>some text</span>");

I use it within the success callback function in $.ajax:

$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $(tag).append(format(html));
    }
});

html give the <span></span> element. I want to retrieve just the text without the tags. I tried it using format(html).text() but it does not work. Any ideas?

Upvotes: 0

Views: 3603

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

$('<span class="opt">some text</span>').text() should do the job or in your case:

$(tag).append($(format(html)).text());

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 237865

If you want to do jQuery operations on a string of HTML, use jQuery to convert it first:

var newContent = $(format(html)); // use the results of `format(html)` to make a jQuery selection
$(tag).append(newContent.text()); // use the jQuery text method to get the text value of newContent

See the API for an explanation of how this works.

Upvotes: 1

davin
davin

Reputation: 45525

$(tag).append($(format(html)).text());

That will take the text "<span>...</span>", convert it into a jQuery object, and extract the text, leaving behind the tags.

Upvotes: 0

Related Questions