0]."/> 0].">

Home  >  Article  >  Web Front-end  >  How to determine whether an object exists in jquery

How to determine whether an object exists in jquery

王林
王林Original
2020-11-24 11:18:572583browse

Jquery method to determine whether an object exists: You can use the length attribute of the jquery object to determine. If [length>0], it means that the object exists, otherwise it means that the object does not exist, such as [$("# id").length>0].

How to determine whether an object exists in jquery

The operating environment of this tutorial: windows10 system, jquery2.2.4 version. This method is suitable for all brands of computers.

(Learning video sharing: javascript video tutorial)

Jquery method to determine whether an object exists:

The specific method is as follows ;

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.

Correct use to determine whether the object exists should be:

if($("#id").length>0){
  //...
}else{
  //...
}

Use the jQuery object's property length to determine, if > 0, it exists.

or

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

Or directly use the native Javascript code to judge:

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

Related recommendations: js tutorial

The above is the detailed content of How to determine whether an object exists in jquery. For more information, please follow other related articles on the PHP Chinese website!

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