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

我现在的代码是:

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

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


当前回答

您可以通过以下方式节省几个字节:

if ($(selector)[0]) { ... }

这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。

其他回答

您可以通过以下方式节省几个字节:

if ($(selector)[0]) { ... }

这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。

Yes!

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

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

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

一个用于id和类选择器的简单实用函数。

function exist(IdOrClassName, IsId) {
  var elementExit = false;
  if (IsId) {
    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
  } else {
    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
  }
  return elementExit;
}

像下面这样调用此函数

$(document).ready(function() {
  $("#btnCheck").click(function() {
    //address is the id so IsId is true. if address is class then need to set IsId false
    if (exist("address", true)) {
      alert("exist");
    } else {
      alert("not exist");
    }
  });
});

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

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

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

在Javascript中

if (typeof selector != "undefined") {
   console.log("selector exists");
} else {
   console.log("selector does not exists");
}

在jQuery中

if($('selector').length){
    alert("selector exists");
} else{
    alert("selector does not exists");
}