如何检查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
}

其他回答

检查jQuery中是否存在元素并不是所有的答案都是无懈可击的。经过多年的编码,只有此解决方案不会对存在与否发出任何警告:

if($(selector).get(0)) { // Do stuff }

或者在你的职能开始时保释:

if(!$(selector).get(0)) return;

解释

在这种情况下,您不必处理零|空长度问题。这会强制获取一个元素,而不是计算它们。

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

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

在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");
}

不需要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

你可以使用这个:

jQuery.fn.extend({
    exists: function() { return this.length }
});

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