提问人:Jake McGraw 提问时间:8/28/2008 最后编辑:RenéJake McGraw 更新时间:8/25/2023 访问量:862273
jQuery是否有“存在”功能?
Is there an "exists" function for jQuery?
问:
如何检查jQuery中元素的存在?
我拥有的当前代码是这样的:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方法来解决这个问题?也许是一个插件或一个函数?
答:
是的!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对以下方面的回应:Jeff Atwood 的 Herding Code 播客
评论
$.fn.exists
.exists
.length
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
评论
如果您使用
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你会暗示链接是可能的,但事实并非如此。
这样会更好:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
或者,从常见问题解答中:
if ( $('#myDiv').length ) { /* Do something */ }
您还可以使用以下命令。如果 jQuery 对象数组中没有值,则获取数组中的第一项将返回 undefined。
if ( $('#myDiv')[0] ) { /* Do something */ }
评论
$(".missing").css("color", "red")
if ( $('#myDiv').size() > 0 ) { //do something }
size()
计算选择器返回的元素数
评论
.size()
.length
.length
.size()
在 JavaScript 中,一切都是“真实的”或“虚假的”,而对于数字来说,意味着 ,其他一切。所以你可以这样写:0
false
true
if ($(selector).length)
你不需要那部分。>0
评论
NaN != false
[].toString() === [].join(',') === ""
"" === ""
NaN != a
a
NaN
可能是,但绝对是假的,这是一件略有不同的事情!= false
NaN
您可以使用以下命令:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
评论
真的不需要jQuery。使用纯 JavaScript 可以更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于任何原因您不想将 id 放入元素,您仍然可以使用任何其他旨在访问 DOM 的 JavaScript 方法。
jQuery真的很酷,但不要让纯JavaScript被遗忘......
评论
检查存在的最快和最语义上自我解释的方法实际上是使用简单的:JavaScript
if (document.getElementById('element_id')) {
// Do something
}
它的编写时间比 jQuery 长度替代方案要长一些,但由于它是原生 JS 方法,因此执行速度更快。
它比编写自己的函数要好。由于@snover所述的原因,这种选择速度较慢。但它也会给其他程序员留下这样的印象,即该函数是jQuery固有的。 会/应该被编辑你的代码的其他人理解,而不会增加知识债务。jQuery
exists()
JavaScript
铌:请注意,在之前缺少“#”(因为这是普通的 JS,而不是 )。element_id
jQuery
评论
$('#foo a.special')
getElementById
if(document.querySelector("#foo a.special"))
我发现是不够的。当是一个空对象时,它会默默地破坏你的应用程序。if ($(selector).length) {}
selector
{}
var $target = $({});
console.log($target, $target.length);
// Console output:
// -------------------------------------
// [▼ Object ] 1
// ► __proto__: Object
我唯一的建议是对 执行额外的检查。{}
if ($.isEmptyObject(selector) || !$(selector).length) {
throw new Error('Unable to work with the given selector.');
}
不过,我仍在寻找更好的解决方案,因为这个解决方案有点重。
编辑:警告!当字符串为字符串时,这在 IE 中不起作用。selector
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
评论
$()
{}
$()
我有一个案例,我想看看一个对象是否存在于另一个对象中,所以我在第一个答案中添加了一些东西来检查选择器中的选择器。
// Checks if an object exists.
// Usage:
//
// $(selector).exists()
//
// Or:
//
// $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
return selector ? this.find(selector).length : this.length;
};
$(selector).length && //Do something
评论
if
if
&&
我正在使用这个:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
仅当 jQuery 元素存在时才执行链 - http://jsfiddle.net/andres_314/vbNM3/2/
此插件可以在类似 callback 的语句中使用,也可以使用回调。if
if ($(ele).exist()) { /* DO WORK */ }
插件
;;(function($) {
if (!$.exist) {
$.extend({
exist: function() {
var ele, cbmExist, cbmNotExist;
if (arguments.length) {
for (x in arguments) {
switch (typeof arguments[x]) {
case 'function':
if (typeof cbmExist == "undefined") cbmExist = arguments[x];
else cbmNotExist = arguments[x];
break;
case 'object':
if (arguments[x] instanceof jQuery) ele = arguments[x];
else {
var obj = arguments[x];
for (y in obj) {
if (typeof obj[y] == 'function') {
if (typeof cbmExist == "undefined") cbmExist = obj[y];
else cbmNotExist = obj[y];
}
if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
if (typeof obj[y] == 'string') ele = $(obj[y]);
}
}
break;
case 'string':
ele = $(arguments[x]);
break;
}
}
}
if (typeof cbmExist == 'function') {
var exist = ele.length > 0 ? true : false;
if (exist) {
return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
}
else if (typeof cbmNotExist == 'function') {
cbmNotExist.apply(ele, [exist, ele]);
return ele;
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
}
else {
if (ele.length <= 1) return ele.length > 0 ? true : false;
else return ele.length;
}
return false;
}
});
$.fn.extend({
exist: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.exist.apply($, args);
}
});
}
})(jQuery);
您可以指定一个或两个回调。如果元素存在,第一个将触发,如果元素不存在,第二个将触发。但是,如果选择仅传递一个函数,则仅当元素存在时才会触发该函数。因此,如果所选元素不存在,链将死亡。当然,如果它确实存在,第一个函数将触发,链将继续。
请记住,使用回调变体有助于保持可链接性 - 返回元素,您可以像使用任何其他 jQuery 方法一样继续链接命令!
示例用法
if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING
if ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT
if ($('#eleID').exist()) { /* DO WORK */ } // enduced on jQuery OBJECT
$.exist('#eleID', function() { // param is STRING && CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}, function() { // param is STRING && CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element DOES NOT EXIST */
})
$('#eleID').exist(function() { // enduced on jQuery OBJECT with CALLBACK METHOD
/* DO WORK */
/* This will ONLY fire if the element EXIST */
})
$.exist({ // param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
element: '#eleID',
callback: function() {
/* DO WORK */
/* This will ONLY fire if the element EXIST */
}
})
评论
Has Items
您可以使用以下命令:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
$.contains()
是你想要的吗?
jQuery.contains( container, contained )
如果第二个参数提供的 DOM 元素是第一个参数提供的 DOM 元素的后代,则该方法返回 true,无论它是直接子元素还是嵌套更深的元素。否则,它将返回 false。仅支持元素节点;如果第二个参数是 text 或 comment 节点,则将返回 false。
$.contains()
$.contains()
注意:第一个参数必须是 DOM 元素,而不是 jQuery 对象或纯 JavaScript 对象。
评论
您可以通过编写以下命令来节省几个字节:
if ($(selector)[0]) { ... }
这是有效的,因为每个 jQuery 对象也伪装成一个数组,所以我们可以使用数组取消引用运算符从数组中获取第一项。如果指定索引处没有项,则返回。undefined
评论
jQuery.first()
jQuery.eq(0)
if(jQuery("#does-not-exist").eq(0)) alert("#does-not-exist exists")
怎么样:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
它非常小,省去了您每次都不得不封闭选择器的麻烦。$()
评论
if($("#thing").exists(){}
我偶然发现了这个问题,我想分享一段我目前使用的代码:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
现在我可以写这样的代码——
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
它可能看起来很多代码,但当用 CoffeeScript 编写时,它非常小:
$.fn.exists = (callback) ->
exists = @length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists
评论
前面所有答案都需要该参数的原因是,它们主要使用 jquery 的选择器,该选择器在窗帘后面有 querySelectorAll(或者他们直接使用它)。这种方法相当慢,因为它需要解析整个 DOM 树,查找与该选择器的所有匹配项,并用它们填充数组。.length
$()
['length'] 参数不是必需的,也不是有用的,如果你直接使用,代码会快得多,因为它返回它匹配的第一个元素,如果没有找到,则返回 null。document.querySelector(selector)
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;
如果你实际上不需要这个元素,只想得到/存储一个真/假,那就加倍吧!它适用于解开的鞋子,那么为什么要在这里打结呢?
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.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
评论
Boolean(x)
您可以在 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
}
评论
尝试测试元素DOM
if (!!$(selector)[0]) // do stuff
受到海威回答的启发,我想出了以下几点:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains 接受两个 DOM 元素,并检查第一个元素是否包含第二个元素。
当我们只想应用它来检查当前文档中元素的存在时,使用作为第一个参数可以满足方法的语义。document.documentElement
exists
下面,我整理了一个片段,将 和 方法进行了比较,这两种方法都返回 while 返回的值。在检查 DOM 中是否存在元素的上下文中,这似乎是期望的结果。jQuery.exists()
$(sel)[0]
$(sel).length
truthy
$(4)
$(4).exists()
false
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
var testFuncs = [
function(jq) { return !!jq[0]; },
function(jq) { return !!jq.length; },
function(jq) { return jq.exists(); },
];
var inputs = [
["$()",$()],
["$(4)",$(4)],
["$('#idoexist')",$('#idoexist')],
["$('#idontexist')",$('#idontexist')]
];
for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
input = inputs[i][1];
tr = "<tr><td>" + inputs[i][0] + "</td><td>"
+ testFuncs[0](input) + "</td><td>"
+ testFuncs[1](input) + "</td><td>"
+ testFuncs[2](input) + "</td></tr>";
$("table").append(tr);
}
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
<td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
$.fn.exists = function() {
return $.contains(document.documentElement, this[0]);
}
</script>
这是我在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
}
);
$("selector"
) 返回一个具有该属性的对象。如果选择器找到任何元素,它们将包含在对象中。因此,如果你检查它的长度,你可以看到是否存在任何元素。在 JavaScript 中,所以如果你没有得到你的代码将运行。length
0 == false
0
if($("selector").length){
//code in the case
}
评论
我只是喜欢使用普通的 javascript 来做到这一点。
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
有 最好的方法:
由:JQuery
if($("selector").length){
//code in the case
}
selector
可以是 ORElement
ID
Element
Class
或
如果你不想使用库,那么你可以通过使用 Core 来实现这一点:jQuery
JavaScript
由:JavaScript
if(document.getElementById("ElementID")) {
//Do something...
}
评论
以下是不同情况的完整示例,以及使用直接 if on jQuery 选择器检查元素是否存在的完整示例,因为它返回数组或元素,因此可能有效,也可能无效。
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
演示
console.log("existing id", $('#id-1').length)
console.log("non existing id", $('#id-2').length)
console.log("existing class single instance", $('.cls-1').length)
console.log("existing class multiple instance", $('.cls-2').length)
console.log("non existing class", $('.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-1 cls-2"></div>
<div class="cls-2"></div>
</div>
评论
使用以下语法通过 jQuery 检查元素是否实际存在。
let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
无需jQuery(基本解决方案)
if(document.querySelector('.a-class')) {
// do something
}
下面性能更高的选项(注意前面缺少一个点)。a-class
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector
使用适当的匹配引擎,如jQuery中的(嘶嘶声),并使用更多的计算能力,但在99%的情况下会做得很好。第二个选项更明确,并确切地告诉代码要做什么。根据 JSBench 的说法,它要快得多 https://jsbench.me/65l2up3t8i$()
检查元素是否存在被整齐地记录在jQuery官方网站本身中!
使用 jQuery 集合的 .length 属性,该集合由 选择器:
if ($("#myDiv").length) { $("#myDiv").show(); }
请注意,并不总是需要测试元素是否存在。 以下代码将显示该元素(如果存在),并且不执行任何操作 (没有错误)如果它没有:
$("#myDiv").show();
我看到这里的大多数答案都不准确,它们检查元素长度,在许多情况下可以,但不是 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
你不必检查它是否大于 like,这就足够了,并且是一种检查元素存在的优雅方式。我不认为只为此写一个函数是值得的,如果你想做更多额外的事情,那么是的。0
$(selector).length > 0
$(selector).length
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
用于 id 和类选择器的简单实用程序函数。
function exist(IdOrClassName, IsId) {
var elementExit = false;
if (IsId) {
elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
} else {
elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
}
return elementExit;
}
像波纹管一样调用此函数
$(document).ready(function() {
$("#btnCheck").click(function() {
//address is the id so IsId is true. if address is class then need to set IsId false
if (exist("address", true)) {
alert("exist");
} else {
alert("not exist");
}
});
});
评论
所有答案都无法检查jQuery中元素的存在。经过多年的编码,只有这个解决方案不会抛出任何关于存在与否的警告:
if($(selector).get(0)) { // Do stuff }
或者在函数开始时保释:
if(!$(selector).get(0)) return;
解释
在这种情况下,您不必处理零 |null 长度问题。这强制获取元素,而不是计算它们。
如果输入不存在,则该输入将没有值。试试这个...
if($(selector).val())
试试这个。
简单短小,可在整个项目中使用:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
甚至更短: (当您不想定义jQuery插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;
与 一起使用,无需额外分配: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($("#element").length > 0){
//the element exists in the page, you can do the rest....
}
它非常简单易行,很容易找到一个元素。
评论
只需检查选择器的长度,如果它大于 0,则返回 true,否则返回 false。
对于ID:
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
对于班级:
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
对于下拉列表:
if( $('#selector option').size() ) { // use this if you are using dropdown size to check
// it exists
}
使用jQuery,您不需要,这就是您所需要的:>0
if ($(selector).length)
使用 vanilla JS,您可以执行相同的操作:
if(document.querySelector(selector))
如果你想把它变成一个返回bool的函数:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}
默认情况下 - 否。
该属性通常用于以下方式获得相同的结果:length
if ($(selector).length)
在这里,“选择器”将被替换为您有兴趣查找的实际选择器,如果它存在与否。如果它确实存在,length 属性将输出一个大于 0 的整数,因此该语句将变为 true,从而执行 if 块。如果没有,它将输出整数“0”,因此 if 块不会被执行。if
评论
我发现这是最jQuery的方式,恕我直言。 扩展默认函数很容易,可以在全局扩展文件中完成。
$.fn.exist = function(){
return !!this.length;
};
console.log($("#yes").exist())
console.log($("#no").exist())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="yes">id = yes</div>
有一种奇怪的现象称为短路调节。没有多少人知道这个功能,所以请允许我解释一下!<3
//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )
//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )
//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({ //return something only if its in the method name
'string':'THIS is a string',
'function':'THIS is a function',
'number':'THIS is a number',
'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')
最后一点允许我查看我的 typeof 具有什么样的输入,并在该列表中运行。如果列表之外有值,我会使用运算符跳过和取消。这与 具有相同的性能,并且被认为有些简洁。测试条件的性能和逻辑运算符的用法。OR (||)
Switch Case
旁注:对象函数有点必须重写>.<' 但是我构建的这个测试是为了研究简洁和富有表现力的条件反射。
评论
感谢您分享这个问题。首先,有多种方法可以检查它。
如果要检查 中是否存在元素。为此,您可以尝试以下方法。HTML
DOM
- 使用选择器:在 DOM 中选择元素 by ,您应该提供以前缀开头的 id 名称。您必须确保 DOM 中的每个 Html 元素都必须具有唯一的 .
Id
id
(#)
id
- 使用选择器:您可以使用前缀 选择属于特定类的所有元素。
class
(.)
现在,如果你想检查元素在 DOM 中是否存在,你可以使用以下代码来检查它。
if($("#myId").length){
//id selector
}
if($(".myClass").length){
//class selector
}
如果要检查任何变量是否未定义。您可以使用以下代码进行检查。
let x
if(x)
console.log("X");
else
console.log("X is not defined");
在 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扩展jQuery。目前(2022 年)的做法是:
jQuery.fn.extend({
exists() { return !!this.length }
});
评论