Get the contents of another div page using jQuery Ajax

I would like page.html ajax-request to contain the side.html file and extract the contents of its two divs. But I can’t find the right way to parse the answer, despite everything I tried.

Here is side.html:

<!DOCTYPE html> <html> <head> <title>Useless</title> </head> <body> <div id="a">ContentA</div> <div id="b">ContentB</div> </body> </html> 

and here is the .html page

 <!DOCTYPE html> <html> <head> <title>Useless</title> <script type='text/javascript' src='jquery-1.9.0.min.js'></script> </head> <body> Hello <script type="text/javascript"> jQuery.ajax({ url: "side.html", success: function(result) { html = jQuery(result); alert(html.find("div#a").attr("id")); alert(html.find("div#a").html()); alert(html.find("div#a")); }, }); </script> </body> </html> 

When I access this page, I get no error, and three warnings () s give undefined, undefined and [object Object]. What am I doing wrong? Example: here .

+8
javascript jquery ajax
source share
2 answers

You need to change this line:

 html = jQuery(result); 

For this:

 html = jQuery('<div>').html(result); 

And actually, even better, you should declare this as a local variable:

 var html = jQuery('<div>').html(result); 

Explanation

When you execute jQuery(result) , jQuery pulls out the children of the <body> element and returns a wrapper around these elements, as opposed to returning a jQuery wrapper for the <html> element, which I tend to agree with, will be pretty dumb.

In your case, <body> sidebar.html contains several elements and some text nodes. Therefore, the jQuery return object is a wrapper for these several elements and text nodes.

When you use .find() , it searches for the descendants of the elements wrapped by the jQuery object you call it on. In your case, <div id="a"> not one of them, because it is actually one of the selected wrapper elements and cannot be a descendant.

By wrapping it in a <div> , you will click these elements one level lower. When you call .find() in my fixed code above, it searches for the descendants of this <div> and therefore finds your <div id="a"> .

A comment

If your <div id="a"> not at the top level, that is, directly a child of <body> , then your code would work. For me, this is inconsistent and therefore incorrect behavior. To solve this problem, jQuery should create a <div> container for you when it works with the magic of extracting <body> content.

+16
source share

Try the following:

 $.get(url,function(content) { var content = $(content).find('div.contentWrapper').html(); ... } 
0
source share

All Articles