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

我现在的代码是:

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

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


当前回答

在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:

if ($(selector).length)

你不需要那>0部分。

其他回答

是的最佳方法:

通过JQuery:

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

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

OR

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

通过JavaScript:

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

我有一个例子,我想看看一个对象是否存在于另一个对象中,所以我在第一个答案中添加了一些东西,以检查选择器中的选择器。。

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};
if ( $('#myDiv').size() > 0 ) { //do something }

size()统计选择器返回的元素数

这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:

jQuery.fn.exists = function(){return !!this.length};

if ($(selector).exists()) {
    // the element exists, now what?...
}

Yes!

jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}

这是对杰夫·阿特伍德主持的《放牧守则》播客的回应