I have an ajax function using jQuery that defines an error function to be called. When an error occurs on the server this error function runs. One of the variables passed in “jqXHR” contains a property called responseText. I want to dump this response text into a div on the page, but the response text contains a fully-formed HTML document. Is there any way to use jQuery to traverse this variable containing HTML in the same way I would traverse the regular DOM?
$.ajax({
blah blah blah...,
error: function (jqXHR, textStatus, errorThrown)
{
var errorText = $(jqXHR.responseText).find('body').html();
// The above line does not work. errorText is NULL.
$('#mainContent').html(errorText);
}
});
I would like to do something like the above code snippet but the way I’m doing it does not work. Is there a way to traverse this variable as if it were a DOM that I could navigate with jQuery?
UPDATE
Here is a console.log($(jqXHR.responseText))
Some sweet discovery for me as well on this one.
This doesn’t work because behind the scenes, jQuery is creating a document fragment and setting the innerHtml property on it. This does not work with the
<html>and<body>nodes because those aren’t document node types–they cannot be placed into the DOM.Instead, when you call
$('<html><body><b>foo</b></body></html>'), a fragment is created with just “<b>foo</b>” in it! So, you want just the body part? Just return:Fiddle to prove what I’m referring to: http://jsfiddle.net/L5PR5/1/
EDIT #2
I think your only choice, given that
<head>elements are being put in there, is to use substrings: