Norse
Norse

Reputation: 5757

How to find an element in AJAX callback with JQuery?

Whenever I try to find say, the body of the returned page from AJAX, it returns null. Here's my JQuery code:

$(document).ready(function(){
$("#button").click(function(){
    $.ajax({
            url: 'testpagec.php', 
            type: 'GET',

            success: function(data) {
                var test = $(data).find('body');
                alert(test.html());

            }
        });
    return false;
});
});

This looks perfect on paper but it's not working as intended. Any ideas on fixing this? Thanks.

Upvotes: 1

Views: 2390

Answers (1)

aziz punjani
aziz punjani

Reputation: 25776

What works for me is this

 var $data = $('<div>').html( data ); 
 $data.find('body'); // this works now

The reason the above works is because body was not an ancestor hence find didn't work, giving the data a root level element will ensure find works. You can also use .filter.

$data.filter('body');  

Upvotes: 4

Related Questions