tags:

views:

114

answers:

2
$('#container').append('<div id="theonly">tests</div>').find('#theonly');

and

$('#container').html('<div id="theonly">tests</div>').find('#theonly');

I'm worried sometimes the dynamically generated elements is not available at once,am I wrong or not?

If I'm not wrong,what's the solution to cover all cases?

EDIT Can someone come up with a definite and unified answer?

A: 

That's why jQuery code is usually in $(document).ready() thing :)

BarsMonster
`ready()` does not guarantee that calls to `html(val)` are immediately available for querying
Matt
+2  A: 

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));
Matt
Then what's your solution?
"YES!" *[runs off cackling maniacally]*
blesh
edited post with a solution you can try
Matt
But I seldom see code like this.Are people all ignoring this corner case?
I imagine people tested the major browsers they were targeting and found their was no issue. That is the correct solution, like I said before.
Matt
ok your solution is probably bulletproof. But i think you guys are a bit paranoïd: the jquery chaining has always proved 100% reliable to me. Except of course in extreme situations (hardware failure of some sort, using internet explorer 1, etc.). I'd be happy to be proven wrong.
pixeline