Is there an “exists” function for jQuery?

前端 未结 30 3014
野性不改
野性不改 2020-11-21 04:52

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}
<         


        
30条回答
  •  囚心锁ツ
    2020-11-21 05:10

    I stumbled upon this question and i'd like to share a snippet of code i currently use:

    $.fn.exists = function(callback) {
        var self = this;
        var wrapper = (function(){
                function notExists () {}
    
                notExists.prototype.otherwise = function(fallback){
                    if (!self.length) {                    
                        fallback.call();
                    }
                };
    
                return new notExists;
            })();
    
        if(self.length) {
            callback.call();    
        }
    
        return wrapper;
    }
    

    And now i can write code like this -

    $("#elem").exists(function(){
        alert ("it exists");
    }).otherwise(function(){
        alert ("it doesn't exist");
    });
    

    It might seem a lot of code, but when written in CoffeeScript it is quite small:

    $.fn.exists = (callback) ->
        exists = @length
        callback.call() if exists        
        new class
           otherwise: (fallback) ->            
                fallback.call() if not exists
    

提交回复
热议问题