Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 444
tvpmb Avatar asked Jan 31 '13 02:01

tvpmb


People also ask

How to check if an element is present in Dom with jQuery?

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]

How to check whether a JavaScript object is a DOM object?

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.

What is getElementsByClassName () in JavaScript?

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.

How to verify if an element exists in DOM using id?

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.


2 Answers

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.

like image 196
Explosion Pills Avatar answered Nov 14 '22 22:11

Explosion Pills


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

if( jQuery(selector).length > 0 ) {
    // exists
}
like image 20
Ricardo Alvaro Lohmann Avatar answered Nov 14 '22 22:11

Ricardo Alvaro Lohmann