简体   繁体   中英

How do I check if an element is in the DOM using a jquery deferred object?

I'm wondering if it is possible to use a jQuery deferred object to test whether or not an element is in the DOM.

Here's kind of what I'm thinking:

function chkDOM(selector) {
  if $(selector) {
    return deferred.promise();
  }
}

$.when(chkDOM(selector)).then(function() {
  // do something
});

I don't exactly know how to form the code to make this happen, but I hope that my question makes sense. If I can get this piece to work right, then I can essentially delay the calling of certain jquery plugins so that they actually run properly.

Thanks!

I assume that you are running a loop that periodically checks the existence of the selector:

var dfd = $.Deferred();
var checkSelector = setInterval(function () {
    if ($("#selector").length) {
        dfd.resolve();
        clearInterval(checkSelector);
    }
}, 1000);

dfd.done(function () {
   console.log('it has been added');
});

Note that $.when is not needed; you can just use .done on the deferred object directly.

You can use the following to check if an element exists.
You don't have to use deferred.

if( jQuery(selector).length > 0 ) {
    // exists
}

To check element in DOM, just use

if($(selector).length > 0) {
// do something

}

$(selector) return an array of elements that match the condition of selector.

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