简体   繁体   中英

How do I check if a jQuery object exists in the DOM?

I want to check if a jQuery object exists in the DOM (with Internet Explorer). I tried this code:

observeEditor = function(editor) {
    function update_position() {
        console.log("update_position");
        var $editor = jQuery(editor);
        if (jQuery(document).find($editor).length > 0) {
            // call our function
            setTimeout(update_position, 250);
        }
    }
    setTimeout(update_position, 250);
};

But the problem is that even after I close the editor (it doesn't exist in the DOM), I still get this console.log every 250 ms. How do I check if the element exists in the DOM? I receive the variable editor as a parameter.

Please notice, the editor may also be inside an <iframe> .

I found a solution, it's not ideal but it works. I gave every editor a unique data attribute:

if (($editor.length === 1) && (typeof($editor.attr('data-editor-id')) === 'undefined')) {
    $editor.attr('data-editor-id', Math.floor((Math.random() * 900000000000000) + 100000000000000));
}

And then I changed the function:

observeEditor = function(editor) {
    var $editor = jQuery(editor);
    var editor_id = undefined;
    if (($editor.length === 1) && (!(typeof($editor.attr('data-editor-id')) === 'undefined'))) {
        editor_id = $editor.attr('data-editor-id');
    }
    function update_position() {
        console.log("update_position");
        if (jQuery(document).find('[data-editor-id="' + editor_id + '"]').length > 0) {
            // call our function
            setTimeout(update_position, 100);
        }
    }
    setTimeout(update_position, 100);
};

By the way, I changed the timout to 100 ms because it's too slow with 250.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM