最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - If selector exists - run code else repeat check - Stack Overflow

programmeradmin3浏览0评论

I'm trying to check if a selector exists, if it does I would like it to run some code, if it doesn't I would like it to repeat the check.

The reason I want to do this is because I know an element WILL exist, but I will not know when.

Something like this:

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

Any ideas?

I'm trying to check if a selector exists, if it does I would like it to run some code, if it doesn't I would like it to repeat the check.

The reason I want to do this is because I know an element WILL exist, but I will not know when.

Something like this:

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

Any ideas?

Share Improve this question edited Aug 21, 2011 at 5:47 Mat 207k41 gold badges401 silver badges416 bronze badges asked Aug 21, 2011 at 5:43 MoDFoXMoDFoX 2,1342 gold badges21 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12
var interval = setInterval(function () {
    if ($(".youtube5player").length) {
        clearInterval(interval);
        // Do stuff
    }
}, 100);

What this does is use setInterval to perform a check approximately every 100 ms to see if your selector returns any results. If it does, the interval is cleared and the code will not run again.

Example: http://jsfiddle/rBdFP/

Besides using setInterval you can also use a recursive setTimeout pattern like the following:

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

While it doesn't seem likely in your case see there are times where using setInterval is considered harmful. From the documentation:

If there is a possibility that your logic could take longer to execute than the interval time, it is remended that you recursively call a named function using window.setTimeout. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from pleting in its alloted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

For such cases, a recursive setTimeout pattern is preferred

发布评论

评论列表(0)

  1. 暂无评论