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

我现在的代码是:

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

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


当前回答

不,没有这样的方法。但是您可以为自己的jQuery扩展jQuery。目前(2022年)的做法是:

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

其他回答

检查是否存在的最快和最语义自解释的方法实际上是使用普通JavaScript:

if (document.getElementById('element_id')) {
    // Do something
}

它比jQuery长度替代方案要长一点,但执行速度更快,因为它是一个原生JS方法。

它比编写自己的jQuery函数要好。出于snover所说的原因,这种替代方案要慢一些。但这也会给其他程序员留下这样的印象:exists()函数是jQuery固有的东西。JavaScript会/应该被其他编辑代码的人理解,而不会增加知识债务。

注意:注意element_id前面缺少“#”(因为这是纯JS,而不是jQuery)。

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

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

前面的所有答案都需要.length参数的原因是,它们主要使用jquery的$()选择器,该选择器在窗帘后面有querySelectorAll(或者直接使用)。此方法相当慢,因为它需要解析整个DOM树,查找与该选择器的所有匹配项,并用它们填充数组。

['length']参数不是必需的或有用的,如果直接使用document.querySelector(selector),代码会更快,因为它返回匹配的第一个元素,如果找不到则返回null。

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;

然而,这个方法留给我们的是实际返回的对象;如果不将其保存为变量并重复使用(因此,如果我们忘记了,就保留引用),这是很好的。

var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.getParentNode.removeChild(myel);
console.log(elementIfExists("#myid")); /* null */
console.log(myel); /* giant table lingering around detached from document */
myel=null; /* now it can be garbage collected */

在某些情况下,这可能是需要的。它可以在for循环中使用,如下所示:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;

如果您实际上不需要该元素,并且只想获取/存储一个true/false,那么就不要加倍!!它适用于松开的鞋子,所以为什么要在这里打结?

function elementExists(selector){
    return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table");  /* will be true or false */
if (hastables){
    /* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
                           alert("bad table layouts");},3000);

$(“selector”)返回一个具有长度属性的对象。如果选择器找到任何元素,它们将包含在对象中。所以如果你检查它的长度,你可以看到是否有元素存在。在JavaScript中,0==false,因此如果没有得到0,代码将运行。

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

实际上不需要jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:

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

如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。

jQuery确实很酷,但不要让纯JavaScript被遗忘。。。