fildred13 fildred13 - 6 months ago 7
HTML Question

Why can't I use part of this AJAX response?

I have a jQuery ajax call:

$.ajax ({
url : 'foo/bar/',
success: function(data) {
console.log(data);

var newHeaderText = $(data).find('#header-text').text();
$("#header-text").text(newHeaderText);

var newContent = $(data).find('#content').html();
console.log(newContent);
$("#content").html(newContent);
}
});


The logged
data
successfully shows the complete html of the target page.

The
header-text
section works as expected.

The
console.log(newContent)
, however, returns
undefined
. Short of posting the entire html of
foo/bar/
here, suffice it to say that I am quite sure a div of id
content
is in
data
, and that it has many child elements.

Why is my attempt at grabbing the content of one page and plopping it into the content of another page not working. It is especially confusing to me as
header-text
seems to work just fine.

Answer

You could try $.parseHTML instead:

var newContent = $($.parseHTML(data)).find('#content');

If #content is a top-level element, then the above code might still miss it. You could then solve this by first loading the HTML in container, and then find the element in there:

var newContent = $('<div>').append($.parseHTML(data)).find('#content');
Comments