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

我现在的代码是:

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

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


当前回答

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

if ($(selector).length)

使用vanilla JS,您可以使用:

if(document.querySelector(selector))

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

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

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

其他回答

将querySelectorAll与forEach一起使用,无需if和额外赋值:

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

与以下内容相反:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}

您不必检查它是否大于0,例如$(selector).length>0,$(selected).llength,这就足够了,是检查元素存在的一种优雅方式。我认为仅为此编写函数是不值得的,如果你想做更多额外的事情,那么是的。

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
if ( $('#myDiv').size() > 0 ) { //do something }

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

您可以使用:

if ($(selector).is('*')) {
  // 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");
    }
  });
});