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

我现在的代码是:

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

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


当前回答

是的最佳方法:

通过JQuery:

if($("selector").length){
   //code in the case
}

选择器可以是元素ID或元素类

OR

如果您不想使用jQuery Library,那么可以通过使用Core JavaScript实现这一点:

通过JavaScript:

if(document.getElementById("ElementID")) {
    //Do something...
}

其他回答

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

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

怎么样:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

它非常简单,而且每次都不用用$()括住选择器。

如果输入不存在,它将没有值。试试这个。。。

if($(selector).val())

我看到这里的大多数答案都不准确,他们检查了元素长度,在很多情况下都可以,但不是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.fn.exists=function(){return !!this[0];}; //jQuery Plugin

用法:

console.log($("element-selector").exists());

_________________________________

或更短:(当您不想定义jQuery插件时):

if(!!$("elem-selector")[0]) ...;

甚至

if($("elem-selector")[0]) ...;