Reputation: 172
I would like page.html to ajax-request the content of side.html and extract the content of two of its divs. But I cannot find the correct way to parse the response, 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 page.html
<!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 the three alert()s yield undefined, undefined and [object Object]. What am I doing wrong? Example is live here.
Upvotes: 8
Views: 41234
Reputation: 9974
Try this :
$.get(url,function(content) {
var content = $(content).find('div.contentWrapper').html();
...
}
Upvotes: 0
Reputation: 4614
You need to change this line:
html = jQuery(result);
To 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 do jQuery(result)
, jQuery pulls the children of the <body>
element and returns a wrapper around those elements, as opposed to returning a jQuery wrapper for the <html>
element, which I tend to agree would be pretty dumb.
In your case, the <body>
of sidebar.html contains several elements and some text nodes. Therefore the jQuery object that is returned is a wrapper for those several elements and text nodes.
When you use .find()
, it searches the descendants of the elements wrapped by the jQuery object that you call it on. In your case, the <div id="a">
is not one of these because it is actually one of the selected elements of the wrapper, and cannot be a descendant of itself.
By wrapping it in a <div>
of your own, then you push those elements "down" a level. When you call .find()
in my fixed code above, it looks for descendants of that <div>
and therefore finds your <div id="a">
.
Comment
If your <div id="a">
was not at the top level, i.e. an immediate child of the <body>
, then your code would have worked. To me this is inconsistent and therefore incorrect behaviour. To solve this, jQuery should generate the container <div>
for you, when it is working its <body>
content extraction magic.
Upvotes: 16