tests').find('#theonly'); and $('#container').html('

Will this code always work?

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

and

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

I sometimes worry that dynamically generated elements are not available right away, am I wrong or not?

If I am not mistaken, what solution should cover all cases?

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

+3
source share
1 answer

In the DOM world, anyone who answers this question with a yes is insane.

The function html(val)replaces directly innerHTML, so theoretically this code should always work, since it #containerwill actually have a new html code at the time of the callfind()

DOM , - . , , .

: : " ?"

, . , , , .

, , HTML , , html() html, .

- :

(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));
+2

Source: https://habr.com/ru/post/1728743/


All Articles