如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
默认情况下-否。
长度属性通常以以下方式用于相同的结果:
if ($(selector).length)
在这里,“选择器”将被您感兴趣的实际选择器替换,无论它是否存在。如果它确实存在,那么length属性将输出一个大于0的整数,因此If语句将变为true,从而执行If块。如果没有,它将输出整数“0”,因此If块不会被执行。
其他回答
是的最佳方法:
通过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
}
一个用于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选择器上的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>
对于jQuery,您不需要>0,这就是您所需要的:
if ($(selector).length)
使用vanilla JS,您可以使用:
if(document.querySelector(selector))
如果要将其转换为返回bool的函数:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}