Following a jQuery ajax call to retrieve an entire XHTML document, what is the best way to select specific elements from the resulting string? Perhaps there is a library or
Inspired from this answer, but with deferred:
function fetchDoc(url) {
var dfd;
dfd = $.Deferred();
$.get(url).done(function (data, textStatus, jqXHR) {
var $iframe = $('').appendTo('body');
var $doc = $iframe.contents();
var doc = $doc[0];
$iframe.load(function() {
dfd.resolveWith(doc, [data, textStatus, jqXHR]);
return $iframe.remove();
});
doc.open();
doc.write(data);
return doc.close();
}).fail(dfd.reject);
return dfd.promise();
};
And smoke it with:
fetchDoc('/foo.html').done(function (data, textStatus, jqXHR) {
alert($('title', this).text());
});
LIVE DEMO (click 'Run')