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

我现在的代码是:

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

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


当前回答

我看到这里的大多数答案都不准确,他们检查了元素长度,在很多情况下都可以,但不是100%,想象一下如果数字传递给函数,所以我原型化了一个函数,它检查所有条件并返回应该的答案:

$.fn.exists = $.fn.exists || function() { 
  return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
}

这将检查长度和类型,现在您可以这样检查:

$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true

其他回答

这里是不同情况的完整示例,以及使用jQuery选择器上的direct-if检查元素是否存在的方法,因为它返回数组或元素,所以它可能工作,也可能不工作。

var a = null;

var b = []

var c = undefined ;

if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
// output: a doesn't exit

if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
// output: b exist

if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
// output: c doesn't exit

最终解决方案

if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist

if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist

Demo

console.log(“现有id”,$('#id-1').length)console.log(“非现有id”,$('#id-2').length)console.log(“现有类单个实例”,$('.cls-1').length)console.log(“现有类多实例”,$('.cls-2').length)console.log(“非现有类”,$('.cls-3').length)<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“id-1”><div class=“cls-1cls-2”></div><div class=“cls-2”></div></div>

前面的所有答案都需要.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扩展jQuery。目前(2022年)的做法是:

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

以下是jQuery中我最喜欢的exist方法

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

以及在选择器不存在时支持回调的其他版本

$.fn.exist = function(onExist, onNotExist) {
    return $(this).each(function() {
        var target = $(this);

        if (this.length > 0) {
            if (typeof onExist === 'function') {
                onExist.call(target);
            }
        } else {
            if (typeof onNotExist === 'function') {
                onNotExist.call(target);
            }
        }
    });
};

例子:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);

默认情况下-否。

长度属性通常以以下方式用于相同的结果:

if ($(selector).length)

在这里,“选择器”将被您感兴趣的实际选择器替换,无论它是否存在。如果它确实存在,那么length属性将输出一个大于0的整数,因此If语句将变为true,从而执行If块。如果没有,它将输出整数“0”,因此If块不会被执行。