Home  >  Article  >  Web Front-end  >  Summary of methods to determine whether an object exists in jQuery_jquery

Summary of methods to determine whether an object exists in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:13:531278browse

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{
  //...
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn