jquery cannot find div by id
i have an ajax call and i am trying to parse the returned page for #viewport, thereby removing the header and footer of the returned page. but find() cannot locate the div.
my original function:
function(event) {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
datatype: "html",
success: function(data) {
alert(data);
var respHTML = $(data).find("#viewport");
开发者_如何转开发 alert(respHTML.length);
$("#contacts_sidebar").html(respHTML);
}
});
return false;
}
in the alert(data), i definitely see <div id="viewport">
, but alert(respHTML.length)
displays 0. if i change the selector to "table.someclass", it would locate it. but selectors such as "head" and "body" returns 0 as well.
i know it's definitely there b/c i replace the success handler with the following workaround:
success: function(data) {
var respHTML;
var d=$(data);
for (i=0; i<d.length; i++) {
if (d[i]["id"] === "viewport") {
respHTML = d[i]["innerHTML"];
break;
}
}
$("#contacts_sidebar").html(respHTML);
}
am i missing something? the workaround works, just ugly.
thanks very much!
If '#viewport'
is at the top level of the response HTML, you'll need .filter()
instead, since .find()
only look inside the top level elements.
success: function(data) {
alert(data);
var respHTML = $(data).filter("#viewport");
alert(respHTML.length);
$("#contacts_sidebar").html(respHTML);
}
When passing HTML to jQuery, you can't rely on finding the <html>
<head>
<body>
tags in a cross browser manner.
If your response does include an entire HTML document, I would pare it down to only the content you actually want if at all possible.
Another option may be to do something like this:
var respHTML = $('<div>' + data + '</div>').find("#viewport");
...but I wouldn't guarantee the result.
You can use the .load() function to parse through the returned page for a specific element.
Check out http://api.jquery.com/load and look at the section about loading page fragments.
精彩评论