If a selector exists, retest the code again

I am trying to check if a selector exists, if so, I would like it to run some code, if it is not, I would like it to repeat the check.

The reason I want to do this is because I know that the element exists, but I will not know when.

Something like that:

if ($(.element).length ) { // Do something }else{ //check again }); 

Any ideas?

+4
source share
2 answers
 var interval = setInterval(function () { if ($(".youtube5player").length) { clearInterval(interval); // Do stuff } }, 100); 

To do this, use setInterval to check approximately every 100 ms to see if your selector returns any results. If so, the interval is cleared and the code will not run again.

Example: http://jsfiddle.net/rBdFP/

+10
source

In addition to using setInterval, you can also use the recursive setTimeout template, for example:

 (function doCheck(){ setTimeout(function(){ if ($(.element).length ) { // Do something }else{ //check again doCheck(); }); }, 100); })(); 

While this does not seem likely in your case, see times when using setInterval is considered harmful. From the documentation :

If it is likely that your logic may take longer to execute than a time interval, it is recommended that you call recursively using the window.setTimeout function. For example, when using setInterval to poll a remote server every 5 seconds, network delays, an unresponsive server, and many other problems may request completion at the appointed time. This way, you can find yourself with XHR requests in the queue, which do not necessarily return in order.

For such cases, the recursive setTimeout pattern is preferred.

+4
source

All Articles