Reputation: 36476
I have the following code:
$(function () {
var html = $('<div></div>');
html.load('preview.html', function (responseText, textStatus, XMLHttpRequest) {
$('#some_id_in_loaded_html')...
}
html.dialog();
}
However in IE7, the jQuery selector in the callback function fails because it can't find the specified ID. It works fine in Firefox.
Why is this occurring and which is the correct behavior (according to the standards)?
Note that this problem is easily corrected by using $('#some_id_in_loaded_html',this)
Upvotes: 2
Views: 135
Reputation: 154908
$("#foo")
uses document
as the context to search in, and as such does not return anything because the html
div (and all its descendants including the element with that ID) are not part of the DOM.
You have to insert the html
div to the DOM first, like html.appendTo("body");
. All descendants are then automatically also in the DOM, and $("#foo")
works.
Test case using actual search function (querySelectorAll
): http://jsfiddle.net/k7muh/.
var div = $("<div><div id='foo'></div></div>");
// tests to expect div#foo
console.log(document.querySelectorAll("#foo")); // searches in document and
// does not find the element
console.log(div.get(0).querySelectorAll("#foo")); // searches in the (detached)
// div and finds the element
Upvotes: 2
Reputation: 71939
In this case, I think it's inserted when you call .dialog()
, which will probably run before your async callback (but perhaps later in some cases?).
Upvotes: 0