如何检查jQuery中元素的存在?

我现在的代码是:

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

有没有更优雅的方式来处理这个问题?也许是插件或函数?


当前回答

怎么样:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

它非常简单,而且每次都不用用$()括住选择器。

其他回答

尝试测试DOM元素

if (!!$(selector)[0]) // do stuff

我偶然发现了这个问题,我想分享一段我目前使用的代码:

$.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;
}

现在我可以编写这样的代码了-

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

它可能看起来有很多代码,但当用CoffeeScript编写时,它非常小:

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

您可以使用此选项:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }

是的最佳方法:

通过JQuery:

if($("selector").length){
   //code in the case
}

选择器可以是元素ID或元素类

OR

如果您不想使用jQuery Library,那么可以通过使用Core JavaScript实现这一点:

通过JavaScript:

if(document.getElementById("ElementID")) {
    //Do something...
}

你可以使用这个:

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something*/}