Trying to find div
element with id=\"result\"
in returned data from .ajax()
using .find()
. Unfortunately, alert(res
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
}
});
try this:
result = $("#result", response);
btw alert
is a rough way to debug things, try console.log
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.
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');
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");