How to check if an element is in the DOM using a pending jquery object?

I am wondering if a jQuery deferred object can be used to check if an element is in the DOM.

That's what I think:

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

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

I donโ€™t know exactly how to generate the code for this to happen, but I hope my question makes sense. If I can get this part to work correctly, I can essentially delay the call of certain jQuery plugins so that they really work correctly.

Thank!

+5
source share
3 answers

I assume that you run a loop that periodically checks for a 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');
});

Please note that it is $.whennot required; you can just use .doneon the deferred object directly.

+7

, , .
.

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

DOM,

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

}

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

0
source

All Articles