Home >Web Front-end >JS Tutorial >Summary of methods to determine whether an object exists in jQuery_jquery
If the following jQuery code is used to determine whether an object exists, it cannot be used.
if($("#id")){ //... }else{ //... }
Because $("#id") will return object regardless of whether the object exists.
To use correctly to determine whether an object exists, use:
if($("#id").length>0){ //... }else{ //... }
Use the length property of the jQuery object to determine if > 0 exists.
or
if($("#id")[0]){ //... }else{ //... }
Or directly use native Javascript code to judge:
if(document.getElementById("id")){ //... }else{ //... }