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

我现在的代码是:

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

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


当前回答

将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');
}

其他回答

Yes!

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

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

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

将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');
}

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

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

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

使用jQuery,使用以下语法检查元素是否确实存在。

let oElement = $(".myElementClass");
if(oElement[0]) {
    // Do some jQuery operation here using oElement
}
else {
    // Unable to fetch the object
}

您可以使用此选项:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }