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

How to determine whether an object exists in jquery

coldplay.xixi
coldplay.xixiOriginal
2020-11-18 11:19:393019browse

Jquery method to determine whether an object exists: 1. Use traditional Javascript writing method, the code is [obj = document.getElementById("someID")]; 2. Use jQuery to determine the object. If it is greater than 0, identify the id. exist.

How to determine whether an object exists in jquery

The operating environment of this tutorial: windows10, jquery2.2.4, this article is applicable to all brands of computers.

How jquery determines whether an object exists:

1. Traditional Javascript writing method

obj = document.getElementById("someID"); 
if (obj){ 
   obj.innerText("hi"); 
}

In jQuery, var obj = $ ("#id")No matter whether the id control exists or not, object is returned, so if(obj) cannot be used to determine whether the control exists

2. jQuery determines whether the object exists

Method 1:

if ($('#target_obj_id').length > 0) {
//如果大于0 标识 id 为target_obj_id的对象存在,否则不存在 
   //对象存在的处理逻辑 
} else { 
   //对象不存在的处理逻辑 
}

Method 2:

if ($('#target_obj_id')[0]) { 
  //对象存在的处理逻辑 
} else { 
  //对象不存在的处理逻辑 
}

Related free learning recommendations: JavaScript (video)

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