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
Instead of hacking jQuery to do this I'd suggest you drop out of jQuery for a minute and use raw XML dom methods. Using XML Dom methods you would can do this:
window.onload = function(){
$.ajax({
type: 'GET',
url: 'text.html',
dataType: 'html',
success: function(data) {
//cross platform xml object creation from w3schools
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(data);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
alert(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
}
});
}
No messing about with iframes etc.
How about some quick tag renaming?
$.ajax({
type : "GET",
url : 'results.html',
dataType : "html",
success: function(data) {
data = data.replace(/html/g, "xhtmlx");
data = data.replace(/head/g, "xheadx");
data = data.replace(/title/g, "xtitlex");
data = data.replace(/body/g, "xbodyx");
alert($(data).find("xtitlex").text());
}
});
After parsing the XML string into an XML DOM
, I'd either use jQuery
on it directly (you can do this by providing a context to the jQUery
selector, such as $(':title', xdoc.rootElement)
or using XPath
(works in Firefox; there are supposedly libraries for IE but I haven't had good success with them).
Inspired from this answer, but with deferred:
function fetchDoc(url) {
var dfd;
dfd = $.Deferred();
$.get(url).done(function (data, textStatus, jqXHR) {
var $iframe = $('<iframe style="display:none;"/>').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')