In the world of DOM, anyone who answers this question with "yes" is insane.
The html(val)
function replaces innerHTML
directly, so in theory this code should always work, since #container
will in fact have the new html code by the time you call find()
However, DOM is notorious for behaving differently across different browsers. So the lesson here is to test thoroughly.
EDIT:
In response to "what is your solution?"
As I said above, you should thoroughly test. The function should work as expected, but you can never be sure without testing the major browsers.
With that said, if you really want a concrete confirmation that the new HTML is ready for querying, you can set up a poll that checks the current html()
against the html you want to set in the first place.
Something like this:
(function ($) {
$.fn.htmlX = function (html, callback) {
var element = this;
var poll = function () {
if (element.html() === html) {
callback();
} else {
setTimeout(poll, 100);
}
};
element.html(html);
poll();
};
$('#container').htmlX('<div id="theonly">tests</div>', function() { $('#container').find('#theonly').css('color', '#f00'); });
}(jQuery));