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

我现在的代码是:

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

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


当前回答

您可以在java脚本中使用长度检查元素是否存在。如果长度大于零,则元素存在;如果长度为零,则元素不存在

// These by Id
if ($("#elementid").length > 0) {
  // Element is Present
} else {
  // Element is not Present
}

// These by Class
if ($(".elementClass").length > 0) {
  // Element is Present
} else {
  // Element is not Present
}

其他回答

我只是喜欢使用普通的javascript来实现这一点。

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}

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

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

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

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

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

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

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

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

将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');
}
if ( $('#myDiv').size() > 0 ) { //do something }

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