58

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]
    }
});
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Mensch
  • 719
  • 1
  • 6
  • 7
  • does the response come in the fist place: `alert(response)`? – Sarfraz Jul 21 '10 at 14:34
  • I don't know how to fix your code in the way you did, but I think it will work if you first put the content inside a div tag with display none and then find the #result tag inside this div. Like: $('#div-content').html(result); $('#div-content').find('#result'); – Keyne Viana Jul 21 '10 at 14:35

17 Answers17

111

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');
Stephen Watkins
  • 25,047
  • 15
  • 66
  • 100
29

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

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
LiveSource
  • 6,230
  • 4
  • 21
  • 20
  • 2
    Actually i think this should have been validated as the correct answer – Cata Cata Apr 19 '12 at 07:43
  • 1
    this is a better solution http://stackoverflow.com/a/13875063/1404348 and worked for me. – MTVS Feb 15 '13 at 17:38
  • this solution worked for me as i had 2 divs being returned as parents. after wrapping them in a single container, the returned html became searchable and traversable. – Lazerblade Feb 18 '13 at 21:39
  • Wrapping the element around a div did the trick, this should be the correct answer! – DirtyBit Mar 30 '18 at 06:37
21

try this:

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

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

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
antpaw
  • 15,444
  • 11
  • 59
  • 88
  • Don't know why but $("#result").replaceWith($(html).find("#result")); didn't work and your answer worked nicely ! – Julien Feb 04 '19 at 11:49
8

this is your answer:

<div class="test">Hello</div>
<div class="one">World</div>    

The following jQuery Won't work:

$(data).find('div.test');    

as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter

$(data).filter('div.test');    

Another same question: Use Jquery Selectors on $.AJAX loaded HTML?

Community
  • 1
  • 1
Nam Nguyen
  • 2,438
  • 21
  • 18
6

do not forget to do it with parse html. like:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        var parsed = $.parseHTML(response);
        result = $(parsed).find("#result");
    }
});

has to work :)

funny
  • 83
  • 1
  • 14
4

This worked for me, you just need to put .html() on the end of - $(response).find("#result")

  • People have not written this useful .html() method to prevent [object object] in alert box. you have mentioned it and this worked 4 me. Thanks. – prashant Jul 18 '17 at 06:16
3

The jQuery find() is returning a jQuery object that wraps the DOM object. You should be able to work with that object to do what you'd like with the div.

Ryan
  • 178
  • 1
  • 5
2

The thing is that your ajax response is returning a string, so if you use directly $(response) it would return JQUERY: Uncaught Error: Syntax error, unrecognized expression in the console. In order to use it properly you need to use first a JQUERY built-in function called $.parseHTML(response). As what the function name implies you need to parse the string first as an html object. Just like this in your case:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        var parsedResponse = $.parseHTML(response);
        var result = $(parsedResponse).find("#result");

        alert(response); // returns as string in console
        alert(parsedResponse); // returns as object HTML in console
        alert(result); // returns as object that has an id named result 
    }
});
1

You can do it in this way to find any div and get its attributes or anything you want.

$(response).filter('#elementtobefindinresponse').attr("id");

or

$(response).filter('img#test').attr("src");
Heart
  • 508
  • 1
  • 3
  • 14
1

Specify dataType: "html".

If you do not jQuery will guess the requested data type (check: http://api.jquery.com/jQuery.ajax/). My guess is that in your case response was a String rather than a DOMObject. Obviously DOM methods won't work on a String.

You could test that with console.log("type of response: " + typeof response) (or alert("type of response:" + typeof response), in case you don't run Firebug)

FK82
  • 4,907
  • 4
  • 29
  • 42
0

Is #result in the response HTML? Try the following. jQuery will still return an empty object if it doesn't find anything.

alert(result.length);
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

You should add dataType: "html" to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.

Fabian
  • 13,603
  • 6
  • 31
  • 53
  • I had a related problem that this didn't solve. I was retrieving an entire web page via AJAX, and either due to a tag or some other malformed issue, jQuery saw the response as a array of text nodes instead of a proper DOM tree. The solution for me was simplifying the response nodes. – Eric_WVGG Jun 02 '15 at 13:10
0

you just use the following code

var response= $(result);

$(response).find("#id/.class").html(); [or] $($(result)).find("#id/.class").html();
Karthikeyan Ganesan
  • 1,901
  • 20
  • 23
0
$.ajax({
    url: url,
    cache: false,
    success: function(response) {
        $('.element').html(response);
    }
});

< span class = "element" >
    //response
    < div id = "result" >
        Not found 
    </div> 
</span>

var result = $("#result:contains('Not found')").text();
console.log(result); // output: Not found
0

try if( $(response).filter('#result').length ) // do something

0

To view the content in alert use:

alert( $(response).find("#result").html() );

Vikram
  • 187
  • 9
-1

You might have to do something like

var content= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d

then you should be able to use

result = $(content).find("#result")
drusnov
  • 363
  • 1
  • 8