如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
尝试测试DOM元素
if (!!$(selector)[0]) // do stuff
其他回答
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
只需检查选择器的长度,如果它大于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
}
$(“selector”)返回一个具有长度属性的对象。如果选择器找到任何元素,它们将包含在对象中。所以如果你检查它的长度,你可以看到是否有元素存在。在JavaScript中,0==false,因此如果没有得到0,代码将运行。
if($("selector").length){
//code in the case
}
这里是不同情况的完整示例,以及使用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>
在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");
}