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'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!
Share Improve this question asked Jan 31, 2013 at 2:48 tvpmbtvpmb 1,4772 gold badges13 silver badges18 bronze badges 3-
This looks wrong
if $(selector) {
... Why using a deferred? What are you trying to do? – elclanrs Commented Jan 31, 2013 at 2:53 - Deferreds are to do with responding to the progress and pletion asynchronous tasks, but I don't perceive any asynchronicity in the scenario described above. – Beetroot-Beetroot Commented Jan 31, 2013 at 3:17
- Thanks for your responses. I missed one key piece, the problem is the DOM element gets injected asynchronously. Appreciate the answer "Explosion Pills" :-) – tvpmb Commented Jan 31, 2013 at 16:40
3 Answers
Reset to default 8I 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.