如何检查 jQuery 中的元素是否存在?
我目前的代码是这样的:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方法来解决这个问题?也许是插件或功能?
如何检查 jQuery 中的元素是否存在?
我目前的代码是这样的:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方法来解决这个问题?也许是插件或功能?
在 JavaScript 中,一切都是“真实的”或“虚假的”,而对于数字0来说false,一切都是如此true。所以你可以写:
if ($(selector).length)
你不需要那>0部分。
是的!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// 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 */ }
你可以使用这个:
// if element exists
if($('selector').length){ /* do something */ }
// if element does not exist
if(!$('selector').length){ /* do something */ }
检查存在的最快和语义上最自我解释的方法实际上是使用 plain JavaScript:
if (document.getElementById('element_id')) {
// Do something
}
它比 jQuery 长度替代方法要长一些,但由于它是原生 JS 方法,所以执行速度更快。
它比编写自己的jQuery函数更好。出于@snover 所述的原因,该替代方案较慢。但它也会给其他程序员留下这样的印象,即该exists()函数是 jQuery 所固有的。JavaScript其他编辑您的代码的人会/应该理解,而不会增加知识债务。
注意:请注意前面缺少“#” element_id(因为这是纯 JS,而不是jQuery)。
您可以通过编写节省几个字节:
if ($(selector)[0]) { ... }
这是因为每个 jQuery 对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一项。undefined如果指定索引处没有项目,则返回。
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
这个插件可以用在类似回调的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 */
}
})
我看到这里的大多数答案都不准确,他们检查元素长度,在很多情况下都可以,但不是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。使用纯 JavaScript,检查以下内容更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于某种原因您不想为元素添加 id,您仍然可以使用任何其他旨在访问 DOM 的 JavaScript 方法。
jQuery 真的很酷,但不要让纯 JavaScript 被遗忘……
你可以使用这个:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
所有前面的答案都需要.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;
如果您实际上并不需要该元素并且只想获取/存储真/假,请不要加倍!它适用于解开的鞋子,那么为什么要在这里打结呢?
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);
是$.contains()你想要的吗?
jQuery.contains( container, contained )如果第二个参数提供的 DOM 元素是第一个参数提供的 DOM 元素的后代,则该
$.contains()方法返回 true,无论它是直接子元素还是嵌套更深的元素。否则,它返回 false。仅支持元素节点;如果第二个参数是文本或评论节点,$.contains()将返回 false。注意:第一个参数必须是 DOM 元素,而不是 jQuery 对象或纯 JavaScript 对象。
您可以在 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
}
我发现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.');
}
我仍在寻找更好的解决方案,因为这个解决方案有点重。
编辑:警告!selector当是字符串时,这在 IE 中不起作用。
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
检查元素是否存在在 jQuery 官方网站本身中有很好的记录!
使用选择器返回的 jQuery 集合的.length属性:
if ($("#myDiv").length) { $("#myDiv").show(); }请注意,并不总是需要测试元素是否存在。以下代码将显示该元素是否存在,如果不存在则不执行任何操作(没有错误):
$("#myDiv").show();
这与所有答案都非常相似,但为什么不使用!两次运算符,以便获得布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
$(selector).length && //Do something
尝试测试DOM元素
if (!!$(selector)[0]) // do stuff
不需要jQuery(基本解决方案)
if(document.querySelector('.a-class')) {
// do something
}
下面的性能更高的选项(注意在 a-class 之前缺少一个点)。
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector 在 jQuery 中使用了一个合适的匹配引擎,比如 $() (sizzle) 并使用了更多的计算能力,但在 99% 的情况下就可以了。第二个选项更明确,并准确地告诉代码要做什么。根据 jsperf https://jsperf.com/getelementsbyclassname-vs-queryselectorall/25,它要快得多
受hiway 的回答启发,我想出了以下内容:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains接受两个 DOM 元素并检查第一个是否包含第二个。
当我们只想应用它来检查当前文档中元素的存在时,document.documentElement作为第一个参数使用满足了该方法的语义。exists
下面,我整理了一个片段,jQuery.exists()用于与$(sel)[0]和$(sel).length方法进行比较,这两种方法都返回truthy了$(4)while$(4).exists()返回的值false。在检查DOM 中是否存在元素的上下文中,这似乎是所需的结果。
$.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>
我只是喜欢使用普通的香草 javascript 来做到这一点。
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
我偶然发现了这个问题,我想分享一段我目前使用的代码:
$.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
我有一个案例,我想看看一个对象是否存在于另一个对象中,所以我在第一个答案中添加了一些东西来检查选择器中的选择器..
// 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;
};
怎么样:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
$()它非常小,并且您不必每次都附上选择器。
我正在使用这个:
$.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/
$("selector") 返回一个具有该length属性的对象。如果选择器找到任何元素,它们将被包含在对象中。因此,如果您检查它的长度,您可以查看是否存在任何元素。在 JavaScript0 == false中,所以如果你没有得到0你的代码将运行。
if($("selector").length){
//code in the case
}
这是我exist在 jQuery 中最喜欢的方法
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
and other version which supports callback when selector does not exist
$.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
}
);
您不必检查它是否大于0like $(selector).length > 0,$(selector).length它就足够了,并且是一种检查元素是否存在的优雅方法。我不认为只为此编写一个函数是值得的,如果你想做更多额外的事情,那么是的。
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
这是不同情况的完整示例以及使用直接 if 在 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.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
甚至更短:(当您不想定义 jQuery 插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;
if ( $('#myDiv').size() > 0 ) { //do something }
size()计算选择器返回的元素个数
是的最好的方法是:
作者JQuery:
if($("selector").length){
//code in the case
}
selector可以是Element ID或Element Class
或者
如果您不想使用jQueryLibrary,那么您可以通过使用 Core 来实现JavaScript:
作者JavaScript:
if(document.getElementById("ElementID")) {
//Do something...
}
一个用于 id 和 class 选择器的简单实用函数。
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");
}
});
});
只需检查选择器的长度,如果大于 0 则返回 true,否则返回 false。
对于身份证:
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中是否存在元素。经过多年的编码,只有这个解决方案不会发出任何关于存在与否的警告:
if($(selector).get(0)) { // Do stuff }
或者在你的函数开始时保释:
if(!$(selector).get(0)) return;
解释
在这种情况下,您不必处理零 | 空长度问题。这会强制获取一个元素,而不是计算它们。
我正在使用这个:
if($("#element").length > 0){
//the element exists in the page, you can do the rest....
}
它非常简单,很容易找到一个元素。
默认情况下 - 否。
有length以下方式通常用于相同结果的属性:
if ($(selector).length)
在这里,“选择器”将替换为您有兴趣查找的实际选择器是否存在。如果它确实存在,length 属性将输出一个大于 0 的整数,因此该if语句将变为 true 并因此执行 if 块。如果没有,它将输出整数 '0',因此 if 块不会被执行。
使用 jQuery,您不需要>0,这就是您所需要的:
if ($(selector).length)
使用 vanilla JS,您可以执行以下操作:
if(document.querySelector(selector))
如果你想把它变成一个返回 bool 的函数:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}
我发现这是最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>
感谢分享这个问题。首先,有多种方法可以检查它。如果要检查HTML元素是否存在于DOM. 为此,您可以尝试以下方法。
Id选择器:在 DOM 中选择元素id,您应该提供以前缀开头的 id 名称(#)。您必须确保 DOM 中的每个 Html 元素都必须具有唯一的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");
有一种奇怪的现象称为短路调节。没有多少人知道这个功能,所以请允许我解释一下!<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 (||)运算符跳过并取消。这与 a 具有相同的性能,Switch Case并且被认为有些简洁。测试条件的性能和逻辑运算符的使用。
旁注:Object-Function 有点需要重写>.<' 但是我建立的这个测试是为了研究简洁和富有表现力的条件。
资源: 逻辑与(带短路评估)
在 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");
}
如果输入不存在,则输入将没有值。试试这个...
if($(selector).val())
使用以下语法检查元素是否使用 jQuery 实际存在。
let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
使用querySelectorAllwith 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');
}