lock
lock

Reputation: 6614

why does jquery .text() always return an empty string?

I have a simple $.ajax call that returns a response that looks like this:

<div id='type'>success</div>
<div id="graph"></div>
<script type='text/javascript'>
   //some script that manipulates the graph div
</script>

and on my .ajax's success(response) function, I have:

$(response).find('#type').text()

my problem is that it always returns null if I use .html()

and 'an empty string' when i use .text();

Is there something wrong with my syntax?

Upvotes: 2

Views: 4640

Answers (5)

Nick Craver
Nick Craver

Reputation: 630379

It's because it's at the root level of the response, so .find() won't work (because it's not a descendant), you need .filter(), like this:

$(response).filter('#type').text()

Upvotes: 9

andres descalzo
andres descalzo

Reputation: 14967

here you can test your code should work fine. you have to have a problem in ajax, try with "alert" to "response" to see what response you get

test

Upvotes: 1

BoltClock
BoltClock

Reputation: 723498

Your response HTML needs to have a root element so that it can find() elements, because find() searches descendants of a DOM element. You can achieve this by adding the response to the document's DOM, or to another jQuery DOM element.

You can also do this and it'll work as well:

$('<div>' + response + '</div>').find('#type').text();

Upvotes: 3

Z. Zlatev
Z. Zlatev

Reputation: 4820

In your $.ajax() request, set dataType as html

Upvotes: 0

Iain
Iain

Reputation: 2309

It cant be something as simple as the single quotes around the id in the type div can it?

(the html, not the js)

Upvotes: 0

Related Questions