Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

Tags:

jquery

find

ajax

Trying to find div element with id="result" in returned data from .ajax() using .find(). Unfortunately, alert(result) doesn't return div#result.

Here is my code:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        result = $(response).find("#result");
        alert(response); // works as expected (returns all html)
        alert(result); // returns [object Object]
    }
});
like image 343
Mensch Avatar asked Jul 21 '10 14:07

Mensch


3 Answers

To answer your question specifically, it seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method. It returns a jQuery element that matches the find query.

Try getting an attribute of that object, like result.attr("id") - it should return result.


In general, this answer depends on whether or not #result is the top level element.

If #result is the top level element,

<!-- #result as top level element -->
<div id="result">
  <span>Text</span>
</div>
<div id="other-top-level-element"></div>

find() will not work. Instead, use filter():

var $result = $(response).filter('#result');

If #result is not the top level element,

<!-- #result not as top level element -->
<div>
  <div id="result">
    <span>Text</span>
  </div>
</div>

find() will work:

var $result = $(response).find('#result');
like image 131
Stephen Watkins Avatar answered Nov 15 '22 13:11

Stephen Watkins


I just spent 3 hours to solve a similar problem. This is what worked for me.

The element that I was attempting to retrieve from my $.get response was a first child element of the body tag. For some reason when I wrapped a div around this element, it became retrievable through $(response).find('#nameofelement').

No idea why but yeah, retrievable element cannot be first child of body... that might be helpful to someone :)

like image 45
LiveSource Avatar answered Nov 15 '22 12:11

LiveSource


try this:

result = $("#result", response);

btw alert is a rough way to debug things, try console.log

like image 21
antpaw Avatar answered Nov 15 '22 13:11

antpaw