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

我现在的代码是:

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

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


当前回答

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

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

其他回答

一个用于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(基本解决方案)

if(document.querySelector('.a-class')) {
  // do something
}

下面的选项性能更高(注意a类前面没有点)。

if(document.getElementsByClassName('a-class')[0]) {
  // do something
}

querySelector在jQuery中使用了一个适当的匹配引擎,比如$()(sizzle),并使用了更多的计算能力,但在99%的情况下都会很好。第二个选项更加明确,并且告诉代码要做什么https://jsbench.me/65l2up3t8i

前面的所有答案都需要.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);

对于jQuery,您不需要>0,这就是您所需要的:

if ($(selector).length)

使用vanilla JS,您可以使用:

if(document.querySelector(selector))

如果要将其转换为返回bool的函数:

const exists = selector => !!document.querySelector(selector);

if(exists(selector)){
  // some code
}

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

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

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