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

Summary of methods to determine whether an object exists in jQuery_jquery

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 15:13:53
Original
1364 people have browsed it

If the following jQuery code is used to determine whether an object exists, it cannot be used.

if($("#id")){
  //...
}else{
  //...
}
Copy after login

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

Use the length property of the jQuery object to determine if > 0 exists.

or

if($("#id")[0]){
  //...
}else{
  //...
}
Copy after login

Or directly use native Javascript code to judge:

if(document.getElementById("id")){
  //...
}else{
  //...
}
Copy after login

Related labels:
Statement of this Website
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
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template