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!
To check if an element is present in DOM with jQuery, you can use the selectors. They return one or more matching elements within a document. Then check the .length property or call the .size () method to get the size of the jQuery object array returned. 2. Using $ (selector) [0]
Approach: In order to check whether a JavaScript object is a DOM object, we need to check whether the given JS object is of Element type Object. In order to check this, we will use instanceof operator.
The Function getElementsByClassName () is used to find the element in the DOM using its class name. An example to the class name value is ClassExample in element <a class="ClassExample"></a>. It will return one or more elements if any element is found or null if the element does not exist.
We can use the function getElementById to verify if an element exists in DOM using the element’s Id. In the following example we will verify that the element <a id="Anchor Id" href="#">Click Here</a> exists in DOM.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With