A method summary in jQuery that determines whether an object exists
- 2021-01-03 20:48:14
- OfStack
If the jQuery code below is used to determine whether an object exists, it is not available.
if($("#id")){
//...
}else{
//...
}
Because $(" #id ") returns object regardless of the object's existence.
The correct use to determine whether an object exists should be:
if($("#id").length>0){
//...
}else{
//...
}
Use the property length of the jQuery object to determine if > Zero exists.
or
if($("#id")[0]){
//...
}else{
//...
}
Or just use the native Javascript code to determine:
if(document.getElementById("id")){
//...
}else{
//...
}